-1

I’m looking at 3 tables here with:

1 called Users containing a UserID.
UserID is linked by a foreign key to UserID in a table called Orders.
Within Orders there’s a PassengerID linked by a foreign key to a table called Passengers.

Is there anyway I can link these tables to identify the UserID it’s associated OrderID and that OrderIDs associated passengerID.

  • Are you asking how to JOIN two tables? – Rick James Nov 2 '18 at 5:01
  • What do you mean with Idetify? – El.Hum Nov 2 '18 at 11:19
  • I’m pretty much asking how I can link my userID in the user table the userID in the orders tables in a join. But I want to join a third table using passengerID in orders table and passengerID in the passenger table – NeillC1234 Nov 3 '18 at 8:06
  • I’m pretty much asking how I can link my userID in the user table the userID in the orders tables in a join. But I want to join a third table using passengerID in orders table and passengerID in the passenger table – NeillC1234 Nov 3 '18 at 8:07
3

This should be straightforward, probably something like this:

SELECT u.UserID, o.OrderID, p.PassengerID
FROM Users u
  JOIN Orders o ON u.UserID=o.UserID
  JOIN Passengers p ON o.PassengerID=p.PassengerID
WHERE ...

The WHERE condition, if you want the WHERE clause at all, could be e.g. u.UserID=5 to retrieve only the results for a certain user, or p.PassengerID=4 for a certain passenger.

A slightly shorter way of writing the same query:

SELECT UserID, o.OrderID, PassengerID
FROM Users u
  JOIN Orders o USING(UserID)
  JOIN Passengers p USING(PassengerID)
WHERE ...

Note that here the aliases u and p are not needed in the SELECT clause. USING can only be used because the columns have identical names in the two tables being joined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.