2012-02-28 107 views
-1

我有一個「更新」表中可以包含重複的描述,我想用自己的計數一起返回重複的,所以我創造了這個查詢:查詢只返回實際重複

SELECT description, count(description) AS count 
FROM updates INNER JOIN participations ON participations.status_id = updates.id 
INNER JOIN customer ON customer.id = participations.customer_id 
INNER JOIN garages ON garages.id = customer.garage_id 
WHERE (updates.created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)) 
GROUP BY description 
ORDER BY count desc 

計數返回的不是我所期待的。我相信之所以會這樣,是因爲許多客戶可以共享更新,所以我得到重複的原因是表中存在實際的重複項,並且因爲同一更新記錄多次返回。如何修復查詢,以便它只計算更新表中的實際重複描述字段。謝謝

+4

您是否考慮刪除JOIN? – 2012-02-28 22:38:25

+0

您是否對不同的客戶或車庫使用相同的描述? – Aprillion 2012-02-29 00:00:20

回答

0

如果我理解正確的和相同的描述用於多個客戶 /車庫,,那麼您需要按所有唯一標識符進行分組,而不僅僅是description

SELECT description, customer.id, garages.id, count(*) AS count 
FROM updates 
JOIN participations ON participations.status_id = updates.id 
JOIN customer ON customer.id = participations.customer_id 
JOIN garages ON garages.id = customer.garage_id 
WHERE (updates.created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)) 

GROUP BY description, customer.id, garages.id 

HAVING count > 1 
ORDER BY count desc 
+0

完美,這個伎倆!謝謝 – pingu 2012-02-29 08:14:53

3

我認爲你可以刪除與參與和車庫,因爲你既不使用它們既不作爲過濾器也沒有得到他們選擇的領域加入。但是,如果你使用它們,那麼就應該做這樣的事情:

SELECT description, count(description) AS count 
FROM updates 
WHERE (updates.created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)) 
    AND EXISTS (SELECT 1 FROM participations INNER JOIN customer ON customer.id = participations.customer_id INNER JOIN garages ON garages.id = customer.garage_id WHERE participations.status_id = updates.id) 
GROUP BY description 
ORDER BY count desc 
1

根據mysql manual你可以使用HAVING條款與GROUP BY生成的字段:

HAVING子句可以引用任何列或在SELECT列表或外部子查詢中的select_expr中命名的別名,以及聚合函數。但是,SQL標準要求HAVING必須僅引用GROUP BY子句中的列或聚合函數中使用的列。

而且例如:

SELECT COUNT(col1) AS col2 FROM t GROUP BY col2 HAVING col2 = 2; 

所以您可以使用您的查詢,如:

SELECT description, count(description) AS count 
FROM updates INNER JOIN participations ON participations.status_id = updates.id 
INNER JOIN customer ON customer.id = participations.customer_id 
INNER JOIN garages ON garages.id = customer.garage_id 
WHERE (updates.created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)) 
GROUP BY description 
HAVING count > 1 
ORDER BY count desc