SELECT * FROM table1 WHERE `id` IN (2,5,8);
假如我要查询ID为2,5,8的3条记录,我希望查到的数据分别是2,5,8为ID的最新的一条数据。这样的SQL应该如何写,谢谢~
都写的很好,但是不能采纳多条答案。
有两种答案,一种是用JOIN ,还有就是目前采纳的临时表的方式。都想采纳,呵呵
现在问题来了,这两种方式的效率哪个高?谢谢
php
select *from table1 WHERE create_time=(select max(create_time) from table1 where `id` IN (2,5,8) group by id);
SELECT * FROM table1 WHERE id IN (2,5,8) order by xxx limit 1;
select t1.* from table1 as t1
right join (
select id, max(createtime) as ctime from table1 group by id
) as t2 on t1.id=t2.id and t1.createtime=t2.ctime
where t2.id in (2,5,8)
一般涉及到同标识多条记录查询最新的记录的问题,就应该有一个时间的字段,比如CREATE_TIME
,我学到一个办法,大概就是结合使用order by
查询最新,group by
归纳成一条记录这种办法。
SELECT * FROM (
SELECT * FROM table1
WHERE `id` IN (2, 5, 8)
ORDER BY `create_time` DESC
) t
GROUP BY t.`id`
不能采纳多条答案。。。都写的很好