简体   繁体   English

内联超过2张桌子

[英]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. 我有5个需要查询的表,我不确定该怎么做。 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. 这些表不是我真正使用的表,在这样的示例中,我只希望使用这些表,并且可以添加很多代码。

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-) 但是要注意,这还没有优化...确实还为时过早... 8-)

You can just continue JOIN ing them... 您可以继续JOIN他们...

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之后添加DISTINCT子句。

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM