Mysql 选择SQL中最常用的项
我有一个mysql数据库,我想选择所有在“名称”和“邮政编码”上相等的值。查询需要选择其他字段中最常见的数据 如果我有:Mysql 选择SQL中最常用的项,mysql,sql,apache,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次,而(t
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
并在查询末尾追加groupbyname,postcode
子句。
查询如下所示:
select ... group by name, postcode
这不是标准SQL,但mysql允许这样做以获得更好的性能:
:
在标准SQL中,包含GROUPBY子句的查询不能引用
选择列表中未在列表中命名的未聚合列
按子句分组。MySQL扩展了GROUPBY的使用,因此
列表可以引用组中未命名的未聚合列
条款这意味着前面的查询在MySQL中是合法的。你可以
使用此功能可以避免不必要的错误,从而获得更好的性能
列排序和分组
当您编写“我需要最常见的数据”时,我将其解释为您正在查找模式平均值,该值只是指定分组列中最频繁出现的数字。这可以通过分组,然后按计数降序排序并选取第一个结果来实现
e、 g
可能应该按
count(*)DESC进行排序,并找到一种方法,每个名称+邮政编码组合只返回一行。但该限制只会影响子查询,外部查询仍将返回多行,其中name=a,postcode=a。Steven Schroeder似乎有一个解决方案。Distinct处理整行,包括子查询列。因此,子查询将在每个名称、邮政编码
组合中被多次求值,然后最终被distinct过滤掉。修复了,我重新阅读了问题,OP不要求有不同的行,也不要求高性能。子查询不引用未聚合的列,因此它是标准SQL+1尽管如此,我似乎是唯一一个在这个问题上投票的人,这感觉不对:S+1一个潜在的问题,因为A1
A2
它可能返回12
,因为11
和22
都只出现一次,并且没有其他鉴别器
SELECT t.name
,t.postcode
,modevaluefortest =
(SELECT t2.test
FROM [table] t2
WHERE t.name = t2.name AND t.postcode = t2.postcode
GROUP BY name, postcode, test
ORDER BY COUNT(*) DESC
LIMIT 1
)
,modevaluefortest2 =
(SELECT t2.test2
FROM [table] t2
WHERE t.name = t2.name AND t.postcode = t2.postcode
GROUP BY name, postcode, test2
ORDER BY COUNT(*) DESC
LIMIT 1
)
FROM [table] t
WHERE t.name = t.postcode -- all values that are equal on "name" and "postcode"
GROUP BY t.name, t.postcode