哪个是解决子组最大值的最佳标准 sql 查询
Which is the best standard sql query to solve maximum in a subgroup
我必须参加考试,即使使用 dbms(MySQL 更准确),查询仍然有效。我在问自己在以下问题中形式上是否正确以及哪种形式更形式上正确,假设 table 如下:
create table T(
k integer primary key not null autoincrement,
camp1 integer not null,
camp2 integer not null);
找到 camp2 的每个值所在的行,其中 camp3 是子集的最大值:
哪个解决方案是正确的,如果两者都是正确的,那么哪个方案在形式上是最好的?
select * from T group by camp2 having camp3 = max(camp3);
或
select * from T b group by camp2 having camp3 = (select max(camp3) from T where T.camp2 = b.camp2);
最好的方法是相关子查询:
select t.*
from t
where t.camp3 = (select max(t2.camp3) from t t2 where t2.camp2 = t.camp2);
特别是,这可以利用 (camp2, camp3)
上的索引。
您的查询应该会产生语法错误,因为它们是格式错误的 SQL 语句——通常不允许将 select *
与 group by
一起使用。特别是,聚合查询 select
中的所有表达式都应该是 group by
键上的表达式,或者它们应该是聚合函数的参数。
尽管以上在广泛的数据库中具有最佳性能(具有正确的索引!),但许多人更喜欢 row_number()
:
select t.*
from (select t.*, row_number() over (partition by camp2 order by camp3 desc) as seqnum
from t
) t
where seqnum = 1;
这也有不错的表现。在更现代的大规模并行数据库(例如 Redshift、BigQuery、PrestoDB)中,它可能具有更好的性能。
我必须参加考试,即使使用 dbms(MySQL 更准确),查询仍然有效。我在问自己在以下问题中形式上是否正确以及哪种形式更形式上正确,假设 table 如下:
create table T(
k integer primary key not null autoincrement,
camp1 integer not null,
camp2 integer not null);
找到 camp2 的每个值所在的行,其中 camp3 是子集的最大值: 哪个解决方案是正确的,如果两者都是正确的,那么哪个方案在形式上是最好的?
select * from T group by camp2 having camp3 = max(camp3);
或
select * from T b group by camp2 having camp3 = (select max(camp3) from T where T.camp2 = b.camp2);
最好的方法是相关子查询:
select t.*
from t
where t.camp3 = (select max(t2.camp3) from t t2 where t2.camp2 = t.camp2);
特别是,这可以利用 (camp2, camp3)
上的索引。
您的查询应该会产生语法错误,因为它们是格式错误的 SQL 语句——通常不允许将 select *
与 group by
一起使用。特别是,聚合查询 select
中的所有表达式都应该是 group by
键上的表达式,或者它们应该是聚合函数的参数。
尽管以上在广泛的数据库中具有最佳性能(具有正确的索引!),但许多人更喜欢 row_number()
:
select t.*
from (select t.*, row_number() over (partition by camp2 order by camp3 desc) as seqnum
from t
) t
where seqnum = 1;
这也有不错的表现。在更现代的大规模并行数据库(例如 Redshift、BigQuery、PrestoDB)中,它可能具有更好的性能。