如何在SQL中实现类似行为?

时间:2012-10-10 13:53:44

标签: mysql sql group-concat

假设我有dogs(dogid)表和fleas(fleaid)表,另一个dogs_favorite_fleas(dogid,fleaid)狗可以在dog_favorite_fleas中列出他最喜欢的跳蚤。如何创建查询/临时表列出所有独特的跳蚤组并计算它们?例如,假设Rex喜欢flea aflea b,而Spot喜欢'跳蚤and跳蚤c , and Lassie likes跳蚤b and跳蚤a`。查询结果应为:

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

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

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

1 个答案:

答案 0 :(得分:2)

GROUP_CONCATGROUP 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 Fiddle Demo

更新:如果您要计算有多少组跳蚤列表,请将上一个查询括在子查询中,并将GROUP BYCOUNT一起使用,如下所示:

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

Updated SQL Fiddle Demo