获取mysql中两列最大值的行

ltskdhd1  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(437)

我有一个包含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万条记录我想担心这个
将为此优化什么查询?

kxkpmulp

kxkpmulp1#

首先你应该创建 indexid 以及 primaryid 然后使用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
p5fdfcr1

p5fdfcr12#

您似乎正在使用sql server。如果是,一种方法是:

select top (1) with ties t.*
from #temp t
order by row_number() over (partition by id order by primaryid desc);
lsmd5eda

lsmd5eda3#

你可以用 subquery 在这里:

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

相关问题