有:
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
然后(计数= 6)和(评级= 3)。
因此计数变为(“计数”乘以“收视率”)。
但我需要 (count= 2 ) 和 ( rating = 3)
我在这里缺少什么?
最佳答案
我自己发现的 首先是 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
关于mysql - sql 在 LEFT JOIN 中使用一个 count() 另一个 count(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20311108/