从 MySQL 的字段中选择最常见的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7693613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 21:16:52  来源:igfitidea点击:

Select most common value from a field in MySQL

mysql

提问by dikidera

I have a table with a million rows, how do i select the most common(the value which appears most in the table) value from a field?

我有一个有一百万行的表,我如何从一个字段中选择最常见的(在表中出现最多的值)值?

回答by Jon

You need to group by the interesting column and for each value, select the value itself and the number of rows in which it appears.

您需要按感兴趣的列进行分组,并为每个值选择值本身及其出现的行数。

Then it's a matter of sorting (to put the most common value first) and limiting the results to only one row.

然后是排序问题(将最常见的值放在首位)并将结果限制为仅一行。

In query form:

在查询表单中:

SELECT column, COUNT(*) AS magnitude 
FROM table 
GROUP BY column 
ORDER BY magnitude DESC
LIMIT 1

回答by Bojangles

This threadshould shed some light on your issue.

这个线程应该对你的问题有所了解。

Basically, use COUNT()with a GROUP BYclause:

基本上,COUNT()GROUP BY子句一起使用:

SELECT foo, COUNT(foo) AS fooCount 
FROM table
GROUP BY foo
ORDER BY COUNT(foo) DESC

And to get only the first result (most common), add

并且只获得第一个结果(最常见),添加

LIMIT 1

To the end of your query.

到您的查询结束。

回答by Philip

In case you don't need to return the frequency of the most common value, you could use:

如果您不需要返回最常见值的频率,您可以使用:

SELECT foo
FROM table
GROUP BY foo
ORDER BY COUNT(foo) DESC
LIMIT 1 

This has the additional benefit of only returning one column and therefore working in subqueries.

这具有仅返回一列并因此在子查询中工作的额外好处。