我有一个 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 允许这样做以获得更好的性能:
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/