加入和条件

时间:2008-11-23 11:16:21

标签: mysql join where

我有以下(缩短查询):

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

现在,FlagCount = 0COUNT(Flags.FlagType)都不适用于WHERE子句。我想过使用SET,但我不确定如何将其添加到查询中。有什么想法吗?

谢谢,

4 个答案:

答案 0 :(得分:5)

答案 1 :(得分:2)

如果HAVING不起作用,也许你可以试试subquerying。

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

答案 2 :(得分:0)

试试这个:

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

答案 3 :(得分:0)

@ eed3si9n

这部分有用 - 但是我需要它是&lt; = 3,这似乎不起作用。

最后执行HAVING子句,它不会返回我需要的结果(由LIMIT设置)。有没有办法可以在WHERE子句中执行此操作?