我有两个表 Service
和 Status
。服务表只保存一个name
和一个id
| id | name | |----|-------| | 1 | Test1 | | 2 | Test2 |
还有一个像这样的状态表
| id | status | service_id | timestamp | |----|--------|------------|---------------------------| | 1 | OK | 1 | October, 15 2015 09:03:07 | | 2 | OK | 1 | October, 15 2015 09:08:07 | | 3 | OK | 2 | October, 15 2015 10:05:23 | | 4 | OK | 2 | October, 15 2015 10:15:23 |
我想获取这样的数据
| id | name | status | timestamp | |----|-------|--------|---------------------------| | 1 | Test1 | OK | October, 15 2015 09:08:07 | | 2 | Test2 | OK | October, 15 2015 10:15:23 |
带有服务数据的最新状态。我已经尝试过这个说法
SELECT ser.id, ser.name, a.status, a.timestamp from Service ser inner join (select * from status order by Status.timestamp DESC limit 1) as a on a.service_id = ser.id
但我只得到
| id | name | status | timestamp | |----|-------|--------|---------------------------| | 2 | Test2 | OK | October, 15 2015 10:15:23 |
如何更改语句以获得我想要的?
用于测试 SQL Fiddle
P粉0236500142023-12-31 18:20:46
对于每项服务,仅当不存在后续服务时,才使用 NOT EXISTS
返回状态:
select ser.id, ser.name, st.status, st.timestamp from service ser left join status st1 on ser.id = st1.service_id where not exists (select 1 from status st2 where st2.service_id = st1.service_id and st2.timestamp > st1.timestamp)
可以选择执行 LEFT JOIN
来返回没有任何状态的服务。如果不需要,请切换到 JOIN
。
P粉7528260082023-12-31 13:53:21
你可以这样做:
SELECT ser.id, ser.name, s.status, s.timestamp FROM Service ser INNER JOIN status as s ON s.service_id = ser.id INNER JOIN ( SELECT service_id, MAX(timestamp) AS MaxDate FROM status GROUP BY service_id ) AS a ON a.service_id = s.service_id AND a.MaxDate = s.timestamp;
与子查询的连接:
SELECT service_id, MAX(timestamp) AS MaxDate FROM status GROUP BY service_id
将消除除最新日期之外的所有状态。