我需要查询5个表,我不确定如何执行此操作。我正在考虑使用多个内连接,但是我遇到了很多错误。
以下是我想要做的一个例子:
表:
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
让我们说这个问题是列出姓名,住在凯悦酒店并继续使用日野公交车的客户状态,我该如何做呢?
表格不是我实际使用的表格,我只是喜欢这样的例子,并且有很多代码可以添加。
答案 0 :(得分:3)
像这样......
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'
但要注意这个没有优化......真的有点不成熟...... 8 - )
答案 1 :(得分:0)
您可以继续JOIN
他们......
根据您的数据,这可能会出现重复项,例如,如果客户住在多家酒店或进行多次旅行,您可能需要重新构建它或在DISTINCT
之后添加SELECT
条款。
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'