我有两张 table ,一张叫做 fruits,里面有:
id title
1 Banana
2 Apple
3 Orange
还有第二个 fruits_chosen:
user_id fruit_id
1 1
2 1
2 3
3 1
3 2
3 3
它应该返回:
Banana 3 times
Orange 2 times
Apple 1 time
现在我构建了一个查询来获取项目,按计数对它们进行排序,但我不知道如何从同一查询中的另一个表中获取标题,有什么想法吗?
"SELECT COUNT(fruit_id) as count, fruit_id FROM fruits_chosen GROUP BY fruit_id ORDER BY COUNT(fruit_id) DESC LIMIT 5"
最佳答案
您将希望使用 fruit_id
到 id
列JOIN
表,类似于此:
SELECT f.title,
COUNT(fc.fruit_id) as count
FROM fruits_chosen fc
INNER JOIN fruits f
on fc.fruit_id = f.id
GROUP BY f.title
ORDER BY COUNT(fc.fruit_id) DESC LIMIT 5
这是使用 INNER JOIN
将只返回在两个表中匹配的那些行。如果你想返回所有的 fruits
而不管它是否被采摘,那么你可以使用 LEFT JOIN
:
SELECT f.title,
COUNT(fc.fruit_id) as count
FROM fruits f
LEFT JOIN fruits_chosen fc
on fc.fruit_id = f.id
GROUP BY f.title
ORDER BY COUNT(fc.fruit_id) DESC LIMIT 5
如果你希望它返回 Banana 3 times
等,你可以使用 MySQL 中的 CONCAT
函数:
SELECT
concat(f.title, ' ',COUNT(fc.fruit_id), ' times') Total
FROM fruits f
LEFT JOIN fruits_chosen fc
on fc.fruit_id = f.id
GROUP BY f.title
ORDER BY COUNT(fc.fruit_id) DESC LIMIT 5
关于mysql - 在其他表中按 id 对 count 和 fetch name 进行排序查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15621285/