我有以下疑问:
SELECT id, MAX(`grab_time`) AS `grab_time` FROM events WHERE ended = false GROUP BY id
这将返回所有具有最大 grab_time 与其他具有相同 id .table events 有四列,我要全部。有人建议我把上面的查询放到子查询中,以便得到缺少的列(它只显示2),但我不知道怎么做?如何让sql基本上“从()中的行中选择行所在的所有内容”?
grab_time
id
events
zbdgwd5y1#
你可以用in作为
select * from events where (id,grab_time) in (SELECT id, MAX(`grab_time`) AS `grab_time` FROM events WHERE ended = false GROUP BY id)
您也可以使用 MAX windows的功能如下:
MAX
select * from ( select t.*, max(grab_time) over (partition by id) as mx from your_table where ended = false ) where grab_time = mx
wydwbb8l2#
一种方法是使用临时表:
with max_time as ( select id,MAX(grab_time) as grab_time FROM events where ended='false' GROUP BY id ) select * from events e,max_time mt where e.id=mt.id and e.grab_time=mt.grab_time;
6gpjuf903#
可以使用相关子查询:
select e.* from events e where not e.ended and e.grab_time = (select max(e2.grab_time) from events e2 where e2.id = e.id and not e2.ended);
你想要索引吗 events(id, ended, grab_time) 用于此查询。或使用 row_number() :
events(id, ended, grab_time)
row_number()
select e.* from (select e.*, row_number() over (partition by id order by grab_time desc) as seqnum from events e where not ended ) e where seqnum = 1;
3条答案
按热度按时间zbdgwd5y1#
你可以用in作为
您也可以使用
MAX
windows的功能如下:wydwbb8l2#
一种方法是使用临时表:
6gpjuf903#
可以使用相关子查询:
你想要索引吗
events(id, ended, grab_time)
用于此查询。或使用
row_number()
: