SQL从具有内部联接和限制的两个表中进行选择

时间:2015-10-15 10:18:54

标签: mysql sql

我有两张表ServiceStatus。服务表仅包含nameid

| 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 |

如何更改语句以获得我想要的内容?

用于测试annotations/decorators

5 个答案:

答案 0 :(得分:1)

你可以这样做:

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

将删除除最新日期之外的所有状态。

答案 1 :(得分:1)

对于每项服务,只有在以后不存在时才使用xmlns:data="HermantsListV2.Model返回状态:

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

答案 2 :(得分:0)

试试这个......

SELECT ser.id, ser.name, a.status, a.max_timesatmp_rm
from Service ser
  inner join (select *,row_number() over (partiton by service_id  order by timestamp  desc ) as max_timesatmp_rm from status
              ) as a
    on a.service_id = ser.id
    where a.max_timesatmp_rm=1;

答案 3 :(得分:0)

您可以在没有子查询的情况下获得该结果

SELECT s.id, s.name, 
SUBSTRING_INDEX(GROUP_CONCAT(st.status ORDER BY st.timestamp DESC),',',1) AS status_value, 
SUBSTRING_INDEX(GROUP_CONCAT(st.timestamp ORDER BY st.timestamp DESC),',',1) AS time_stamp
FROM Service s
JOIN Status st ON(st.service_id = s.id)
GROUP BY s.id
ORDER BY s.id

输出

id  name    status_value    time_stamp
1   Test1   OK            2015-10-15 09:08:07
2   Test2   OK            2015-10-15 10:15:23

答案 4 :(得分:0)

您可以使用此查询获得结果

SELECT MAX(s.id),
  sr.id, 
  sr.name, 
  s.status, 
  s.timestamp 
FROM Service AS sr 
INNER JOIN status AS s ON s.service_id = sr.id
GROUP BY sr.id
ORDER BY s.id ASC

我认为它适合你