一个count()的sql在LEFT JOIN中的另一个count()

时间:2013-12-01 10:20:36

标签: mysql count left-join distinct

具有:

SELECT *, COUNT(MakeModel) as `count`
FROM (`table_a`)
GROUP BY `MakeModel`
ORDER BY `count` DESC

适合我(计数= 2) 使用LEFT JOIN扩展此查询,如下所示:

SELECT *, COUNT(distinct b.rating) as ratings
FROM (`table_a`)
LEFT JOIN `model_ratings` AS b ON `b`.`MakeModel` = `table_a`.`MakeModel`
GROUP BY `table_a`.`MakeModel`

也工作正常(评分= 3), 但结合这两个计数:

SELECT *, COUNT(table_a.MakeModel) as `count`, COUNT(distinct b.rating) as ratings
FROM (`table_a`)
LEFT JOIN `model_ratings` AS b ON `b`.`MakeModel` = `table_a`.`MakeModel`
GROUP BY `table_a`.`MakeModel`
ORDER BY `count` DESC

然后(count = 6)和(rating = 3)。

因此计数变为('计数'次'评级')。

但我需要(count = 2)和(rating = 3)

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

由我自己找到 LEFT JOIN中的COUNT()和GROUP首先

SELECT *, COUNT(table_a.MakeModel) as `count`, b.rating as ratings
FROM (`table_a`)
LEFT JOIN (
   SELECT MakeModel, COUNT(distinct rating)
   FROM `model_ratings`
   GROUP BY MakeModel
   ) AS b ON `b`.`MakeModel` = `table_a`.`MakeModel`

GROUP BY `table_a`.`MakeModel`
ORDER BY `count` DESC