mysql - 在其他表中按 id 对 count 和 fetch name 进行排序查询

标签 mysql count

我有两张 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_ididJOIN 表,类似于此:

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

参见 SQL Fiddle with Demo

这是使用 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

参见 SQL Fiddle with Demo

如果你希望它返回 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

参见 SQL Fiddle with Demo

关于mysql - 在其他表中按 id 对 count 和 fetch name 进行排序查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15621285/

相关文章:

php - 拉维尔 4 : many to many (insertion)

php - 多对多关系 MYSQL - 根据用户输入选择数据,例如症状

javascript - 作为参数传递的最长字符串的长度

sql - 在 Rails 中进行计数的正确方法是什么?

mysql查询需要不同的结构

mysql - 查询 : Select and display next highest value as new column

jQuery - 实时更新长度,而不是仅在页面加载时更新

sql - 如何从具有特定组计数的表中获取所有行?

mysql - 如何计算每天相同的日期值

子查询中的 MySQL 未知列