原题:
select * from table1 where `id` in (2,5,8);假如我要查询id为2,5,8的3条记录,我希望查到的数据分别是2,5,8为id的最新的一条数据。这样的sql应该如何写,谢谢~
给出的答案有以下两种:
1.一般涉及到同标识多条记录查询最新的记录的问题,就应该有一个时间的字段,比如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`
2.select t1.* from table1 as t1right join ( select id, max(createtime) as ctime from table1 group by id) as t2 on t1.id=t2.id and t1.createtime=t2.ctimewhere t2.id in (2,5,8)
第一种没有聚合函数的情况下使用group by。
第二种有使用max()聚合函数
这两种得到的结果都是预期的。但是第一种这样使用是否是正确的,会产生错误的结果吗?
回复内容: 原题:
select * from table1 where `id` in (2,5,8);假如我要查询id为2,5,8的3条记录,我希望查到的数据分别是2,5,8为id的最新的一条数据。这样的sql应该如何写,谢谢~
给出的答案有以下两种:
1.一般涉及到同标识多条记录查询最新的记录的问题,就应该有一个时间的字段,比如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`
2.select t1.* from table1 as t1right join ( select id, max(createtime) as ctime from table1 group by id) as t2 on t1.id=t2.id and t1.createtime=t2.ctimewhere t2.id in (2,5,8)
第一种没有聚合函数的情况下使用group by。
第二种有使用max()聚合函数
这两种得到的结果都是预期的。但是第一种这样使用是否是正确的,会产生错误的结果吗?
第一种是错误的. 按mysql 的说法, 返回的结果应该是此分组中 随机的一个. 执行的时候确实是 得到了预期的结果, 但mysql 不保证你 一定给你预期的结果.