限制三重连接的结果

时间:2012-12-28 17:59:03

标签: sql sqlite

我有一个包含三个表的数据库,与外键相关:

行程:

| ID| Number| Date|
------------------

天:

| ID| TripID| Date| Start| End|
------------------------------

腿:

| ID| DayID| Origin| Destination|
--------------------------------

我使用以下连接从此数据库中获取数据:

SELECT * FOM Trips t JOIN Days d
    ON t.Id = d.TripId
JOIN Legs l 
    ON d.Id = l.DayId
WHERE t.Id = tripId

返回一个结果,该结果包含与查询行程关联的每条腿的一行,如下所示:

| Trips.ID| Trips.Number| Trips.Date| Days.ID| Days.TripID| Days.Date| Days.Start| Days.End| Legs.ID| Legs.DayID| Legs.Origin| Legs.Destination|
-------------------------------------------------------------------------------------------------------------------------------------------------

这适用于特定旅行ID,但是我说我运行一个返回多次旅行的查询,例如

    SELECT * FROM Trips t JOIN Days d
       ON t.ID = d.TripID
    JOIN Legs l
       ON d.Id = l.DayId
    WHERE d.Date > date

如何将上述查询的结果限制为单次旅行,但仍然获得与该旅行相关联的所有行?

1 个答案:

答案 0 :(得分:1)

我不是100%肯定sqlite语法(我对oracle更熟悉),但我认为这就是你想要的:

SELECT * FROM Trips t JOIN Days d
ON t.ID = d.TripID
JOIN Legs l
ON d.Id = l.DayId
WHERE d.ID IN (  
    SELECT ID FROM Days d WHERE d.date > date ORDER BY d.date LIMIT 1
)