MYSQL:如何选择列中出现的最高值?

时间:2011-01-12 19:39:06

标签: php mysql sql

我有一个包含电影列表的mysql表。我想用php在网页上显示票数或出现次数最多的电影。我怎么能这样做?

title
Toy Story 3
Toy Story 3
Toy Story 3
Inception
Inception 

例如:应显示的值为“玩具总动员3”

4 个答案:

答案 0 :(得分:9)

select title, count(*) as cnt from films group by title order by cnt desc limit 1

答案 1 :(得分:4)

SELECT title, count(*) as count
FROM films
GROUP BY title
ORDER BY count DESC
LIMIT 1

这将计算每个标题的行数,并仅返回最高标题。如果您希望返回的所有标题按标题的最大数量排序,请删除限制。

此查询将返回如下内容:

+-------------+-------+
| title       | count |
+-------------+-------+
| Toy Story 3 |     3 |
+-------------+-------+

答案 2 :(得分:2)

SELECT title,COUNT(title) AS cnt
 FROM Film
 GROUP BY title
 HAVING cnt=(SELECT COUNT(title) as count
              FROM Film
             GROUP BY title
             ORDER BY count desc limit 1);

这个将返回所有碰巧分享最大数量的电影。

答案 3 :(得分:1)

select f.title, f.cnt as count 
from
( select title, count(*) as cnt
from films f
group by title ) f
, ( select max(count(*)) mcnt
FROM films 
GROUP BY title ) f2
where f.cnt = f2.mcnt

这个将返回所有碰巧分享最大数量的电影