在SQL中加入第三个表

时间:2014-05-13 19:24:14

标签: mysql sql join inner-join

在下面的查询中,我正在尝试SELECT Destination_City.Name_,为此需要将Destination_City.Destination_City_ID加入Contract_Items.Destination_City_ID,但后一个表已经与{{1}内联表格。

Contract

基本上表2需要加入表3,但表2已经加入表1.我尝试了几种不同的方法,但都抛出了错误,我不知道如何编写这个查询。

2 个答案:

答案 0 :(得分:1)

Name_列加入DESTINATION_CITY表格应该没问题:

SELECT 
    contract.Description,
    Destination_City.Name_,
    contract_type.type AS 'Contract Type',
    contract.Tour_Summary AS 'Tour Name',
    employee.First_Name AS 'First Name',
    employee.Last_name AS 'Last Name',
    Currency_.Currency_Name AS 'Currency',
    contract_Items.twin AS 'Twin Rate',
    contract_items.Item_Rate AS 'Rate'
FROM 
    Contract
        INNER JOIN Employee 
            ON Contract.Contracted_By_Employee_Id = Employee.Employee_Id
        INNER JOIN Contract_Items
            ON Contract.Contract_ID = Contract_Items.Contract_ID
        INNER JOIN Currency_
            ON Contract.Currency_Id = Currency_.Currency_Id
        INNER JOIN Contract_Type
            ON Contract.Contract_Type_Id = contract_type.Contract_Type_Id
        INNER JOIN Destination_City
            ON Destination_City.Destination_City_ID = Contract_Items.Destination_City_ID

请注意,如果您只有内部联接,则联接操作的顺序无关紧要。它之前只需要其中一个表已加入。

答案 1 :(得分:0)

此?

FROM Contract
    INNER JOIN Employee 
        ON Contract.Contracted_By_Employee_Id = Employee.Employee_Id
    INNER JOIN Contract_Items
        ON Contract.Contract_ID = Contract_Items.Contract_ID
    INNER JOIN Destination_City ON
        Destination_City.Destination_City_ID = Contract_Items.Destination_City_ID
    INNER JOIN Currency_
        ON Contract.Currency_Id = Currency_.Currency_Id
    INNER JOIN Contract_Type
        ON Contract.Contract_Type_Id = contract_type.Contract_Type_Id