在MySql中获取具有两列最大值的行

时间:2018-05-04 10:35:14

标签: 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'),
       (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万条记录,我想担心这个

对此进行优化查询的内容是什么?

3 个答案:

答案 0 :(得分:2)

您可以在此处使用subquery

select * 
from #temp t
where primaryid = (select max(tt.primaryid) from #temp tt where tt.id = t.id);

答案 1 :(得分:1)

您似乎正在使用SQL Server。如果是这样,一种方法是:

creed

答案 2 :(得分:0)

首先,您应该在indexid上创建primaryid,然后按以下方式使用加入:

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