SQL:自连接表 SELECT 中的前 1 个? (或者更好的方法......)
这可能之前已经讨论过(或者太简单了),但我找不到一个简单的答案:应该如何做到这一点:选择每个 id 的(单个)最早的未来日期和最近的日期?
t1: ==?==> (earliest) (most recent)
|id|date(DESC)| |id|future_date | past_date |
+==+==========+ +==+=============+===============+
|1 | d1 | | 1| d1 | d3 |
|2 | d2 | | 2| d2 | d6 |
(<==now) | 3| | d4 |
|1 | d3 |
|3 | d4 |
|1 | d5 |
|2 | d6 |
我正在思考以下内容,但我感觉这是相当复杂/糟糕的语法,而且我还没有弄清楚如何限制单个结果(即最近/最近的未来)。有什么建议吗?
SELECT t_1.id,t_1.date AS future_date,t_2.date AS past_date
FROM (SELECT * FROM t1 WHERE t1.date>CURRENT_TIMESTAMP) t_1
LEFT OUTER JOIN
(SELECT TOP 1 * FROM t1 WHERE t1.date<CURRENT_TIMESTAMP) t_2
ON t_1.id=t_2.id
This has probably been discussed before (or it's too simple), but I can't find an easy answer: How should this be done: select the (single) earliest future date and most recent date per id?
t1: ==?==> (earliest) (most recent)
|id|date(DESC)| |id|future_date | past_date |
+==+==========+ +==+=============+===============+
|1 | d1 | | 1| d1 | d3 |
|2 | d2 | | 2| d2 | d6 |
(<==now) | 3| | d4 |
|1 | d3 |
|3 | d4 |
|1 | d5 |
|2 | d6 |
I was thinking along the lines of the following, but I have the feeling that this is rather complicated/bad syntax, and I haven't figured out how to limit to single results (i.e. most recent/nearest in future). Any suggestions?
SELECT t_1.id,t_1.date AS future_date,t_2.date AS past_date
FROM (SELECT * FROM t1 WHERE t1.date>CURRENT_TIMESTAMP) t_1
LEFT OUTER JOIN
(SELECT TOP 1 * FROM t1 WHERE t1.date<CURRENT_TIMESTAMP) t_2
ON t_1.id=t_2.id
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你可以使用:
不清楚你正在使用什么数据库 - TOP 仅是 TSQL/SQL Server 语法(2000+),而 NOW 作为
NOW()
由 MySQL 和 PostgreSQL 支持。 CURRENT_TIMESTAMP 是 ANSI,并且受到所有支持。I think you could use:
It's unclear what database you're working with - TOP is TSQL/SQL Server syntax only (2000+), while NOW as
NOW()
is supported by MySQL and PostgreSQL... CURRENT_TIMESTAMP is ANSI, and supported by all.为什么这不起作用?
why wouldn't this work?