1

假设我有dogs(dogid)一张桌子和fleas(fleaid)一张桌子,而另一张桌子上dogs_favorite_fleas(dogid,fleaid)的狗可以将他最喜欢的跳蚤列在dog_favorite_fleas. 如何创建一个查询/临时表列出所有独特的跳蚤集并计算它们?例如,让我们说Rex喜欢flea aflea b,并且Spot喜欢“跳蚤 aand跳蚤 c , andLassielikes跳蚤 band跳蚤 a”。查询的结果应该是:

fleas          |count
-------------------------
flea a, flea b |2
flea a, flea c |1

注意:有约 5000 种不同的跳蚤和约 450 万只狗。

进行此查询的最佳方法是什么?

4

1 回答 1

2

GROUP_CONCAT与 一起使用GROUP BY

SELECT GROUP_CONCAT(f.flea SEPARATOR ', ') AS 'fleas', COUNT(df.dogid) 'Count'
FROM dogs_favorite_fleas df 
INNER JOIN fleas f ON df.fleaid = f.id
INNER JOIN dogs d ON df.dogid = d.id
GROUP BY df.dogid

SQL 小提琴演示

更新:如果您想计算有多少分组跳蚤列表,请将上一个查询包含在子查询中并使用GROUP BYwithCOUNT像这样:

SELECT fleas, COUNT(fleas) 'COUNT'
FROM
(
   SELECT GROUP_CONCAT(f.flea SEPARATOR ', ') AS 'fleas'
   FROM dogs_favorite_fleas df 
   INNER JOIN fleas f ON df.fleaid = f.id
   INNER JOIN dogs d ON df.dogid = d.id
   GROUP BY df.dogid
   ORDER BY f.flea
) t
GROUP BY fleas

更新的 SQL Fiddle 演示

于 2012-10-10T13:56:37.163 回答