Brandyn
Brandyn

Reputation: 1017

Inner joining on more than 2 tables

I have 5 tables that I need to query from, and I am unsure how to do this. I was considering using multiple inner joins, however i was getting thrown lots of errors.

Here is an example of what I want to do:

Tables:

Customer
ID  Name      State  hotelID
1   George    W.A    1
2   Franklin  N.S.W  2

Bus
ID  Make
1   Hino
2   Mercedes
3   Leyland

Hotel
ID  Name
1   Hyatt
2   Sebel

Tour
ID  tourName busID
1   Japan    1
2   America  1
3   Austria  2


tour-CustLink
ID tourID custID
1   1     1
2   2     2
3   3     3

Let's say the query is to list names, state of customers who stayed at the Hyatt and went on Hino buses, how would I go about doing this?

The tables are not what I am actually working with, I'd just prefer it in an example like this, and there is way to much code to add.

Upvotes: 0

Views: 80

Answers (2)

Matthew
Matthew

Reputation: 10444

You can just continue JOINing them...

This may present duplicates depending on your data, you may need to restructure it or add a DISTINCT clause after the SELECT if the customer stayed in multiple hotels or went on multiple tours, for example.

SELECT
    c.[name]
    ,c.[state]
FROM
    Customer AS c
JOIN
    Hotel AS h
        ON h.[ID] = c.[hotelID]
JOIN
    tour-CustLink AS tcl
        ON tcl.[CustID] = c.[ID]
JOIN
    Tour AS t
        ON t.[ID] = tcl.[tourID]
JOIN
    Bus AS b
        ON b.[ID] = t.[BusID]
WHERE
    b.[Make] = 'Hino'
    AND h.[name] = 'Hyatt'

Upvotes: 0

softwarebear
softwarebear

Reputation: 451

Something like this ...

SELECT c.Name, c.State
FROM tourCustLink AS tcl
INNER JOIN Customer AS c ON tcl.custID = c.ID
INNER JOIN Hotel AS h on c.hotelID = h.ID
INNER JOIN Tour AS t on tcl.tourID = t.ID
INNER JOIN Bus AS b on t.busID = b.ID
WHERE h.Name = 'Hyatt'
AND b.Make = 'Hino'

But beware this is not optimised ... a bit premature really ... 8-)

Upvotes: 3

Related Questions