views:

33

answers:

1

I'm trying to SELECT two values in one statement instead of two statements. The first statement counts how many entries won for a specific contest that has an id of 18. The second statement counts the total quantity of prizes for that contest.

Query 1:

SELECT 

COUNT(*) FROM entries 

WHERE entries.contest=18

AND entries.won=1

Query 2

SELECT SUM( quantity ) FROM prizes WHERE contest=18

I want to have both so I could compare them on the server-side and act upon that comparison.. So if we had say 3 entrants who won the 18th contest and the total quantity of prizes for the 18th contest is 5, do something...

Schema:

CREATE TABLE `entries` (
  `id` int(2) unsigned NOT NULL auto_increment,
  `message_id` bigint(8) unsigned default NULL,
  `user` int(2) unsigned default NULL,
  `username` varchar(50) NOT NULL,
  `contest` int(2) unsigned default NULL,
  `message` text,
  `icon` text,
  `twitter_url` text,
  `follower` int(2) unsigned default NULL,
  `entry_date` timestamp NOT NULL default '0000-00-00 00:00:00',
  `won` int(1) default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

CREATE TABLE `prizes` (
  `id` int(2) unsigned NOT NULL auto_increment,
  `name` varchar(25) NOT NULL,
  `contest` int(2) NOT NULL,
  `quantity` int(2) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

There is no users table because I control the entries, and I'm pretty sure I won't get any duplicates so that's why the user name, etc is stored for the entry row.

+2  A: 

As the queries doesn't have anything in common at all, you would use two subqueries to get them in the same result:

select
  (select count(*) from entries where contest = 18 and won = 1) as wins,
  (select sum(quantity) from prizes where contest = 18) as quantity
Guffa
Awesome, thank you. I just realized that I'm not really tracking who won what prize, instead only just if an entrant won or not, `won` by default is 0. Should I set `won` to be the pk of the prizes instead of `1`?
meder
Hm, was just thinking that 0 or 1 could be a pk, I could also update the prizes table so the `id` pk starts at 2. Would be great if you could chime in.
meder
@meder: Instead of a "win" field, you could have a "prize_id" field that is nullable. A null value would be a more obvious indicator for a non-win than a magic number like zero.
Guffa
Excellent idea, I'll make the necessary schema changes. Thanks.
meder