tags:

views:

140

answers:

4

I have the following (shortened query):

SELECT 
    `Statistics`.`StatisticID`,
    COUNT(DISTINCT `Flags`.`FlagType`) AS `FlagCount`
FROM `Statistics`
LEFT JOIN `Flags` ON `Statistics`.`StatisticID` = `Flags`.`StatisticID`
WHERE `FlagCount` = 0
GROUP BY `Statistics`.`StatisticID`
ORDER BY `SubmittedTime` DESC
LIMIT 0, 10

Now, neither FlagCount = 0 or COUNT(Flags.FlagType) work in the WHERE clause. I thought about using a SET but I'm not sure how I'd add that to the query. Any ideas?

Thanks,

+5  A: 

Use HAVING COUNT(DISTINCT Flags.FlagType) = 0.

eed3si9n
Brilliant - thanks!
Ross
Ah this only works with = 0 - is there a way to make it work with <= 3 for example?
Ross
A: 

Try this:

SELECT 
    `Statistics`.`StatisticID`,
    COUNT(DISTINCT `Flags`.`FlagType`) AS `FlagCount`
FROM `Statistics`
LEFT JOIN `Flags` ON `Statistics`.`StatisticID` = `Flags`.`StatisticID`
                     And `FlagCount` = 0
GROUP BY `Statistics`.`StatisticID`
ORDER BY `SubmittedTime` DESC
LIMIT 0, 10
A: 

@eed3si9n

This partially works - however I need it to be <= 3 which doesn't seem to work.

Also the HAVING clause is executed last which won't return as many results as I need (as set by LIMIT). Is there a way I can do this in a WHERE clause instead?

Ross
Please show exactly what you tried, and say how it doesn't work.http://dev.mysql.com/doc/refman/5.0/en/select.html: "The HAVING clause is applied nearly last, just before items are sent to the client, with no optimization. (LIMIT is applied after HAVING.)"
ysth
+1  A: 

Maybe you can try subquerying if HAVING doesn't work.

SELECT 
 `Statistics`.`StatisticID`,
 COUNT(DISTINCT `Flags`.`FlagType`) AS `FlagCount`
FROM `Statistics`
 LEFT JOIN `Flags` ON `Statistics`.`StatisticID` = `Flags`.`StatisticID`
WHERE `Statistics`.`StatisticID`
  IN (SELECT `Flags`.`StatisticID` 
   FROM `Flags`
   HAVING COUNT(DISTINCT `Flags`.`FlagType`) <= 3
   GROUP BY `Flags`.`StatisticID`
  )
GROUP BY `Statistics`.`StatisticID`
ORDER BY `SubmittedTime` DESC
LIMIT 0, 10
eed3si9n
I think this is getting to the right approach - except it returns result that only have greater than or 3 flags. I'll play around with it.
Ross
I removed the GROUP BY in the sub-select and changed IN to NOT IN and it seems to work. The main reason HAVING doesn't work is because it doesn't seem to support gt/lt values (or I'm doing something strange). HAVING should work in most cases though.
Ross