如何从MySQL中选择食物中最常食用的部分?

时间:2013-03-19 19:43:23

标签: mysql

我有一张名为eaten的餐桌,里面有吃过的食物,如下:

id | food | amount
1    1      50
2    1      60
3    1      60
4    1      70
5    2      10
6    2      1
7    2      900
8    2      1
9    2      1
10   3      3

我需要为每个amount选择最常见的food。这是预期的结果:

food | amount
1      60
2      1
3      3

这是我的MySQL查询,但只适用于一种食物:

SELECT `food`, `amount`, COUNT(`amount`) as `count`
FROM `eaten`
WHERE `food` = 1
GROUP BY `amount`
ORDER BY `count` DESC
LIMIT 1

出于某种原因,当我删除WHERE部分时,返回的值不正确。我该如何解决这个问题?

这是重新创建数据库以测试它的SQL文件:eaten.sql

3 个答案:

答案 0 :(得分:2)

尝试:

select rq.food, rq.amount 
from (select food, amount, count(*) amcount
      from eaten
      group by food, amount) rq
join (select food, max(amcount) maxcount from
      (select food, amount, count(*) amcount
       from eaten
       group by food, amount) sq
      group by food) mq
on rq.food = mq.food and rq.amcount = mq.maxcount

Sql Fiddle

答案 1 :(得分:1)

另一种方式:

SELECT
    e.*
FROM
    ( SELECT DISTINCT food
      FROM eaten
    ) AS d
  JOIN
    ( SELECT DISTINCT food, amount
      FROM eaten
    ) AS e
      ON e.amount =
         ( SELECT amount
           FROM eaten AS ee
           WHERE ee.food = d.food
           GROUP BY amount
           ORDER BY COUNT(*) DESC
               LIMIT 1
         ) ;

SQL-Fiddle

进行测试

答案 2 :(得分:-1)

这应该为您提供每种食物类型的最常见量。子选择将给出每种食物和数量的总和。在主循环中,GROUP BY子句将确保查询仅返回每种食物类型一条记录。 ORDER BY将使它成为最常见的一个。

SELECT `food`, `amount`, `count`

FROM

(
    SELECT `food`, `amount`, COUNT(`amount`) as `count`
    FROM `eaten`
    GROUP BY `food`, `amount`
    ORDER BY `food`, `count` DESC
) x

GROUP BY `food`
;