2012-07-01 235 views
3

這是我的查詢MySQL COUNT(*)GROUP BY HANDING COUNT =?

SELECT COUNT(*) as total, toys, date FROM T1 
WHERE (date >= '2012-06-26'AND date < '2012-06-30') AND (Avail > '0') 
UNION 
SELECT COUNT(*) as total, toys, date FROM T2 
WHERE (date >= '2012-06-26'AND date < '2012-06-30') AND (Avail > '0') 
UNION 
SELECT COUNT(*) as total, toys, date FROM T3 
WHERE (date >= '2012-06-26'AND date < '2012-06-30') AND (Avail > '0') 
GROUP BY RoomType 
HAVING COUNT(total) = 4 

輸出結果

count Toys   date 
3 Bibi  2012-06-26 
4 Baba   2012-06-26 

我怎樣才能讓MySQL只顯示計數= 4

回答

4
SELECT * FROM (
    SELECT COUNT(*) as total, toys, date FROM T1 
    WHERE (date >= '2012-06-26' AND date < '2012-06-30') AND (Avail > '0') 
    GROUP BY RoomType 
    UNION 
    SELECT COUNT(*) as total, toys, date FROM T2 
    WHERE (date >= '2012-06-26' AND date < '2012-06-30') AND (Avail > '0') 
    GROUP BY RoomType 
    UNION 
    SELECT COUNT(*) as total, toys, date FROM T3 
    WHERE (date >= '2012-06-26'AND date < '2012-06-30') AND (Avail > '0') 
    GROUP BY RoomType) AS src 
WHERE total = 4; 

請,請注意,對於正確的數據groupping結果您必須必須具有GROUP BY子句中的所有列或作爲聚合函數的參數。 MySQL允許您避免這種限制,但它可能會導致您意想不到的結果。

4

您需要先按組合然後合併結果。

SELECT COUNT(*) as total, toys, date FROM T1 
WHERE (date >= '2012-06-26'AND date < '2012-06-30') AND (Avail > '0') 
GROUP BY RoomType HAVING COUNT(*) = 4 
UNION 
SELECT COUNT(*) as total, toys, date FROM T2 
WHERE (date >= '2012-06-26'AND date < '2012-06-30') AND (Avail > '0') 
GROUP BY RoomType HAVING COUNT(*) = 4 
UNION 
SELECT COUNT(*) as total, toys, date FROM T3 
WHERE (date >= '2012-06-26'AND date < '2012-06-30') AND (Avail > '0') 
GROUP BY RoomType HAVING COUNT(*) = 4 
+0

謝謝oooooooooooooooooooo你是最棒的!!!!!!!!!!!!!!!!! – user1478893