我有一个“更新”表,可以包含重复的描述,我想返回重复项及其计数,所以我创建了这个查询:
SELECT description, count(description) AS count
FROM updates INNER JOIN participations ON participations.update_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))
AND garages.`id` = 1
GROUP BY description
ORDER BY count desc
LIMIT 10
返回的计数并不是我所期待的。我相信原因是因为许多客户可以共享更新,因此我会因为表中的实际重复而得到重复,并且因为多次返回相同的更新记录。如何修复查询以使其仅计算更新表中的实际重复描述字段。感谢
答案 0 :(得分:1)
您可能会重写您的查询以使用EXISTS,因为您需要客户才能到达车库: - )
SELECT description, count(description) AS count
FROM updates
WHERE (updates.created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH))
AND EXISTS (select null from participations INNER JOIN customer ON customer.id = participations.customer_id WHERE participations.update_id = updates.id AND customer.garage_id = 1)
GROUP BY description
ORDER BY count desc
LIMIT 10