2008-11-23 60 views
1

我有以下的(簡稱查詢):聯接和那裏的條件

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 = 0WHERE子句中COUNT(Flags.FlagType)工作。我想過使用SET,但我不知道如何將它添加到查詢中。有任何想法嗎?

感謝,

回答

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 
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 
0

@ eed3si9n

這部分作品 - 但我需要它是< = 3這似乎並沒有工作。

此外HAVING子句最後執行,它不會返回儘可能多的結果,因爲我需要(由LIMIT設置)。有沒有辦法可以在WHERE條款中做到這一點?

+0

請準確顯示您嘗試過的內容,並說明它不起作用。 http://dev.mysql.com/doc/refman/5.0/en/select.html:「HAVING子句幾乎是最後一次應用,就在將項目發送給客戶端之前,沒有進行優化。(LIMIT在HAVING。)「 – ysth 2008-11-23 15:18:14