此查询(InvoiceID)出现不明确的列名错误。我无法弄清楚为什么。它们似乎都正确连接,为什么管理工作室不知道显示VendorID?任何帮助将不胜感激。
查询:
SELECT
VendorName, InvoiceID, InvoiceSequence, InvoiceLineItemAmount
FROM 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
答案 0 :(得分:39)
我认为你只在InvoiceID中有歧义。其他领域似乎不同。所以试试这个
我只需用Invoices.InvoiceID
替换InvoiceID SELECT
VendorName, Invoices.InvoiceID, InvoiceSequence, InvoiceLineItemAmount
FROM 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, Invoices.InvoiceID, InvoiceSequence, InvoiceLineItemAmount
您可以对所有列使用tablename.columnnae(在选择,where,group by和order by中),而不使用任何别名。但是,您可以在其他答案的指导下使用别名
答案 1 :(得分:8)
InvoiceID
表格和Invoices
表格中都有一列InvoiceLineItems
。查询执行引擎无法知道您想要返回哪一个。
添加表别名将有助于:
SELECT V.VendorName, I.InvoiceID, IL.InvoiceSequence, IL.InvoiceLineItemAmount
FROM Vendors V
JOIN Invoices I ON (...)
JOIN InvoiceLineItems IL ON (...)
WHERE ...
ORDER BY V.VendorName, I.InvoiceID, IL.InvoiceSequence, IL.InvoiceLineItemAmount
答案 2 :(得分:5)
因为您要加入两个包含InvoiceID的表Invoices和InvoiceLineItems。更改为Invoices.InvoiceID以使其正确。
答案 3 :(得分:4)
两个表最有可能都有一个具有相同名称的列。对每个表进行别名,并使用表别名调用每个列。
答案 4 :(得分:4)
这是因为某些字段(特别是发票表 Invoices表和 InvoiceLineItems 上)存在于两个表中。回答问题的方法是在其上添加ALIAS
。
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
答案 5 :(得分:0)
您的一个表具有相同的列名,这使查询中您要引用的表的列混乱。复制此代码并运行它。
SELECT
v.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount
FROM Vendors AS v
JOIN Invoices AS i ON (v.VendorID = .VendorID)
JOIN InvoiceLineItems AS iL ON (i.InvoiceID = iL.InvoiceID)
WHERE
I.InvoiceID IN
(SELECT iL.InvoiceSequence
FROM InvoiceLineItems
WHERE iL.InvoiceSequence > 1)
ORDER BY
V.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount
答案 6 :(得分:0)
This happens because there are fields with the same name in more than one table, in the query, because of the joins, so you should reference the fields differently, giving names (aliases) to the tables.