mysql - 选择 SQL 中最常见的项目

标签 mysql sql apache

我有一个 mysql 数据库,我想选择“名称”和“邮政编码”上相同的所有值。并且查询需要选择其他字段中最常见的数据。

如果我有:

name postcode test  test2
a    a        1     2
a    a        1     2
a    a        2     1
a    a        1     1
a    a        1     1

然后这需要返回

a    a        1     1

因为(test)1在表中出现了4次,而(test2)1则出现了3次。所以我需要列中最常见的数据,其中名称和邮政编码相同。

最佳答案

这是我的第一个方法:

select distinct
    name, 
    postcode, 
    (select 
       s.test
    from 
       your_table s
    where
       name s.name = m.name, s.postcode = m.postcode
    group by 
       s.name, s.postcode, s.test
    order by count(*) desc
    limit 1 ) as test,
    (select 
       s.test2
    from 
       your_table s
    where
       name s.name = m.name, s.postcode = m.postcode
    group by 
       s.name, s.postcode, s.test2
    order by  count(*) desc
    limit 1 ) as test2
from your_table m

如果您不需要高性能,这是一个解决方案。如果经常执行此查询,那么您应该寻找其他方法。

已编辑

如果您需要更高的性能并且需要不同的行,则可以删除 distinct 并在查询末尾附加 group by name, postcode 子句。 查询如下:

select ... group by name, postcode

这不是标准 SQL,但 mysql 允许这样做以获得更好的性能:

Quoting MySQL doc :

In standard SQL, a query that includes a GROUP BY clause cannot refer to nonaggregated columns in the select list that are not named in the GROUP BY clause. MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. This means that the preceding query is legal in MySQL. You can use this feature to get better performance by avoiding unnecessary column sorting and grouping.

关于mysql - 选择 SQL 中最常见的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9342304/

相关文章:

MySQL子查询问题

sql - Postgresql - 列数未知的数据透视表

linux - 如何预压缩非常大的html文件

php - 计算价格范围内的订单,并按周数分组

apache - 有没有办法删除apaches反向代理请求 header ?

php - 通过php函数readfile下载大文件不起作用

所有行上的 MySQL GROUP BY 条件(不是 WHERE 或 HAVING)

javascript - 成功的 ajax 返回后模态框不会关闭

php - 收到错误消息,由于错误,我的图像无法显示

两次选择的MySQL连接结果