假设我有dogs(dogid)
表和fleas(fleaid)
表,另一个dogs_favorite_fleas(dogid,fleaid)
狗可以在dog_favorite_fleas
中列出他最喜欢的跳蚤。如何创建查询/临时表列出所有独特的跳蚤组并计算它们?例如,假设Rex
喜欢flea a
和flea b
,而Spot
喜欢'跳蚤and
跳蚤c , and
Lassie likes
跳蚤b and
跳蚤a`。查询结果应为:
fleas |count
-------------------------
flea a, flea b |2
flea a, flea c |1
注意:有大约5000种不同的跳蚤和~450万只狗。
进行此查询的最佳方式是什么?
答案 0 :(得分: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
更新:如果您要计算有多少组跳蚤列表,请将上一个查询括在子查询中,并将GROUP BY
与COUNT
一起使用,如下所示:
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