简体   繁体   English

选择具有MAX(时间戳)的行

[英]Select the row with MAX(timestamp)

In our database we have addresses, services and missions. 在我们的数据库中,我们有地址,服务和任务。 Simplified, our data looks like this: 简化后,我们的数据如下所示:

Adress:
id
name

Service:
id
Address_id

Mission:
id
start
Service_id

What I tried to achieve is getting the Mission.id of the Mission that started last for each address. 我要实现的目标是获取每个地址最后开始的Mission.id。 Every address can be in multiple services and each service can have multiple missions. 每个地址可以位于多个服务中,并且每个服务可以具有多个任务。 I tried many different ways, but none of which worked. 我尝试了许多不同的方法,但是没有一种有效。 My latest attempt: 我最近的尝试:

SELECT
  a.id AS addressID,
  m.id AS missionID
FROM Address AS a
JOIN Service AS s ON s.Address_id = a.id
JOIN Mission AS m ON m.Service_id = s.id AND m.start = (SELECT MAX(start) FROM Mission WHERE start < ".time().")

The problem is, that multiple missions start at the same time, so I'm randomly joining any mission with the the correct start, but it's not guaranteed that it really belongs to my address. 问题是,多个任务会同时开始,因此我会以正确的开始随机加入任何任务,但不能保证它确实属于我的住址。 Any tips / inputs are highly welcome. 任何提示/输入都非常欢迎。

I think you want a correlated subquery, for the approach you are using. 我认为您要使用的是相关的子查询。 I think the logic is: 我认为逻辑是:

SELECT a.id AS addressID, m.id AS missionID
FROM Address a JOIN
     Service s
     ON s.Address_id = a.id JOIN
     Mission m
     ON m.Service_id = s.id
WHERE m.start = (SELECT MAX(m2.start)
                 FROM Mission m2 JOIN
                      Service s2
                      ON m2.Service_Id = s2.id
                 WHERE s2.Address_Id = s.AddressId AND
                       m2.start < ".time()."
                );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM