[英]Fetch the row which has the Max value for two column in MySql
i have a table which contains id , primaryid , data ,dataname columns i want only rows for which contains max id and primaryid 我有一个包含id,primaryid,data和dataname列的表,我只希望包含最大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'),
(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')
i achieve this with below query 我通过以下查询实现了这一点
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
but my table have more than 100k records i want to worry about that 但是我的桌子上有超过10万条记录,我想为此担心
What will be optimized query for this? 什么将对此进行优化查询?
You may use subquery
here : 您可以在此处使用subquery
:
select *
from #temp t
where primaryid = (select max(tt.primaryid) from #temp tt where tt.id = t.id);
You appear to be using SQL Server. 您似乎正在使用SQL Server。 If so, one method is: 如果是这样,一种方法是:
select top (1) with ties t.*
from #temp t
order by row_number() over (partition by id order by primaryid desc);
First you should create index
on id
and primaryid
and then use join as below: 首先,您应该在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.