id
note
created_at
在sql语言中是否有一种方法尤其是Postgres,我可以选择最后一个音符的值而不必使用LIMIT 1?
正常查询:
select note from table order by created_at desc limit 1
我对避免限制的事情感兴趣,因为我需要它作为子查询.
解决方法:
如果您的id列是自动增量主键字段,那么它非常简单.这假设最新音符具有最高ID. (这可能不是真的;只有你知道!)
select *
from note
where id = (select max(id) from note)
它在这里:MysqL为http://sqlfiddle.com/#!2/7478a/1/0,postgresql为http://sqlfiddle.com/#!1/6597d/1/0.相同的sql.
如果你的id列没有设置,所以最新的音符具有最高的id,但仍然是一个主键(也就是说,每行中仍然有唯一的值),这有点困难.我们必须消除相同日期的歧义;我们将通过任意选择最高的id来做到这一点.
select *
from note
where id = (
select max(id)
from note where created_at =
(select max(created_at)
from note
)
)
这是一个例子:http://sqlfiddle.com/#!2/1f802/4/0 for MysqL.
这是postgresql(sql是一样的,是的!)http://sqlfiddle.com/#!1/bca8c/1/0
另一种可能性:如果它们都是在同一时间创建的,那么您可能希望将两个音符一起显示在一行中.再一次,只有你知道.
select group_concat(note separator '; ')
from note
where created_at = (select max(created_at) from note)
在postgresql 9中,它是
select string_agg(note, '; ')
from note
where created_at = (select max(created_at) from note)
如果你确实有重复创建的时间和重复的id值,并且你不想要group_concat效果,那么你很可能会遇到LIMIT.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。