在其他表中通过id按顺序查询计数和获取名称

时间:2013-03-25 17:41:03

标签: mysql count

我有两张桌子,一张叫做水果:

id title

1  Banana
2  Apple
3  Orange

还有第二个水果_选择:

   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"

2 个答案:

答案 0 :(得分:2)

您需要使用JOINfruit_idid表格,类似于:

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

答案 1 :(得分:1)

SELECT 
COUNT(*) as count,
f.title, 
fruit_id 
FROM fruits_chosen fc
INNER JOIN fruits f on f.id = fc.fruit_id
GROUP BY 
fc.fruit_id, f.title
ORDER BY count DESC 
LIMIT 5

SqlFiddle