Khantahr
Khantahr

Reputation: 8528

Limiting results of a triple join

I have a database with three tables, related with foreign keys:

Trips:

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

Days:

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

Legs:

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

I get data out of this database using the following join:

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

Which returns a result containing one row for each leg associated with the queried trip that looks like:

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

This works fine for a specific trip ID, but say I run a query that returns multiple trips, for example

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

How can I limit the result of the above query to a single trip, but still get all the rows associated with that trip?

Upvotes: 0

Views: 147

Answers (1)

Gerrat
Gerrat

Reputation: 29690

I'm not 100% sure about the sqlite syntax (I'm more familiar with oracle), but I think this is what you want:

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
)

Upvotes: 1

Related Questions