从子查询中选择具有最大值的行,而不使用LIMIT

时间:2016-11-24 18:36:12

标签: mysql sql

假设我有一张表电影(电影,类别)。 我想找到电影最多的类别。我怎么做而不使用LIMIT?

我想我可以这样做:

SELECT category
FROM
(SELECT category, COUNT(*) AS num
FROM films
GROUP BY category) AS T1
WHERE num =
(SELECT MAX(num)
FROM
(SELECT category, COUNT(*) AS num
FROM films
GROUP BY category) AS T2) 

但有更优雅的方式吗?最好是一个我不必多次写同一个子查询的地方?

谢谢!

(如果你想知道为什么我不能使用LIMIT,那就是做作业)

1 个答案:

答案 0 :(得分:1)

您可以使用变量创建行号:

SELECT category
FROM
    (
       SELECT
          category
          COUNT(*) as NumOfFiles
          ,(@rn:= @rn + 1) as RowNumber
       FROM
          Films f
          CROSS JOIN (SELECT @rn:=0) vars
       GROUP BY
          category
       ORDER BY
          COUNT(*) DESC
    ) t
WHERE
    t.RowNumber = 1