Query error with ambiguous column name in SQL

前端 未结 8 804
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 06:54

I get an Ambiguous column name error with this query (InvoiceID). I can\'t figure out why. They all seem to be joined correctly so why doesn\'t the management studio know to

8条回答
  •  鱼传尺愫
    2020-11-27 07:34

    it's because some of the fields (specifically InvoiceID on the Invoices table and on the InvoiceLineItems) are present on both table. The way to answer of question is to add an ALIAS on it.

    SELECT 
        a.VendorName,  Invoices.InvoiceID, .. -- or use full tableName
    FROM Vendors a   -- This is an `ALIAS` of table Vendors
    JOIN Invoices ON (Vendors.VendorID = Invoices.VendorID)
    JOIN InvoiceLineItems ON (Invoices.InvoiceID = InvoiceLineItems.InvoiceID)
    WHERE  
        Invoices.InvoiceID IN
            (SELECT InvoiceSequence 
             FROM InvoiceLineItems
             WHERE InvoiceSequence > 1)
    ORDER BY 
        VendorName, InvoiceID, InvoiceSequence, InvoiceLineItemAmount
    

提交回复
热议问题