每个左连接返回1个结果

时间:2010-09-17 21:34:40

标签: sql join filter left-join

目前我正在两个表上执行左连接。第一个表有一个id和一个人名,第二个表有一个id,一个人的id来自表1,然后是一个时间戳(他们最后一次飞行)。

People                             Flights
id   |  name             id   |   person_id   | time
------------             ---------------------------
1       Dave              1         1          1284762115
2       Becky             2         1          1284787352
                          3         2          1284772629
                          4         2          1286432934
                          5         1          1289239480

当我执行左连接时,我会得到一个人员列表和他们的航班时间,但我想要的只是他们上次航班时间的人员列表。

所以SELECT p.id,p.name,f.time FROM People p LEFT JOIN Flights f ON p.id = f.person_id

返回

1 Dave  1284762115
1 Dave  1284787352
1 Dave  1289239480
2 Becky 1284772629
2 Becky 1286432934

我想看到:

1 Dave  1289239480
2 Becky 1286432934

所以我只需要返回最高f.id或最高f.time

的匹配

3 个答案:

答案 0 :(得分:5)

SELECT
    p.id, p.name, MAX(f.time) AS LastFlight
FROM
    People p
    LEFT JOIN Flights f ON p.id = f.person_id
GROUP BY
    p.id, p.name

答案 1 :(得分:2)

SELECT p.id, p.name, f.time FROM People p LEFT JOIN 
  (select person_id, max(time) time from flights group by person_id) f 
ON p.id = f.person_id

答案 2 :(得分:1)

试试这个:

;with LastFlightTimes as 
(
select person_id, max(id) maxid
from Flights f
group by person_id
)
SELECT p.id, p.name, f.time FROM People p 
LEFT JOIN LastFlightTimes lft ON p.id = lft.person_id
left join Flights f on f.id = lft.maxid