获取MySql中两列最大值的行
我有一个表,其中包含我想要的id、primaryid、data和dataname列 仅包含max id和primaryid的行获取MySql中两列最大值的行,mysql,sql,greatest-n-per-group,query-performance,sqlperformance,Mysql,Sql,Greatest N Per Group,Query Performance,Sqlperformance,我有一个表,其中包含我想要的id、primaryid、data和dataname列 仅包含max id和primaryid的行 create table #temp ( id int, primaryid int, data nvarchar(20), data_name nvarchar(30) ) insert into #temp values (1,1,'3223sfd','434'),(1,2,'sdfsd','dfsdfsd'),
create table #temp
(
id int,
primaryid int,
data nvarchar(20),
data_name nvarchar(30)
)
insert into #temp
values (1,1,'3223sfd','434'),(1,2,'sdfsd','dfsdfsd'),
(1,3,'sdfs897d','898'),(1,4,'898','545'),(1,5,'898','uuyu'),
(2,1,'3223sfd','434'),(2,2,'sdfsd','dfsdfsd'),
(2,3,'sdfs897d','898'),(2,4,'898','545'),(2,5,'898','uuyu')
我通过下面的查询实现了这一点
select T.id , T.primaryid , T.data , T.data_name from #temp T , (select ID, max(primaryid) rank from #temp t2 group by id ) as T2
where t.primaryid = t2.rank group by T.id , T.primaryid , T.data , T.data_name
但是我的表有超过10万条记录,我想担心这一点
此查询将优化哪些内容?您可以在此处使用
子查询
:
select *
from #temp t
where primaryid = (select max(tt.primaryid) from #temp tt where tt.id = t.id);
首先,您应该在
id
和primaryid
上创建index
,然后按如下方式使用join:
SELECT T.id , T.primaryid , T.data , T.data_name FROM #temp T
JOIN (select id, max(primaryid) as primaryid from #temp t2 group by id ) as T2
ON T.id = t2.id and t.primaryid = t2.primaryid
您似乎正在使用SQL Server。如果是,一种方法是:
select top (1) with ties t.*
from #temp t
order by row_number() over (partition by id order by primaryid desc);
您的代码无效。您真正使用的是什么数据库?@Gordon Linoff使用MSSQL,但将代码迁移到MySQLyou查询时,在“;”附近的上下文中指定了一个非布尔类型的表达式@尼提什库马尔。。。使用
orderby
而不是where
子句。这是两个数据库的最佳解决方案。