處理SQL 查詢中不明確的列名
透過連接從多個表中擷取資料時,可能會遇到指示列不明確的錯誤訊息姓名。當兩個或多個連接表中存在相同的列名時,就會發生這種情況,使查詢解釋器不確定要引用哪個表。
例如,在提供的查詢中,InvoiceLineItems 和 Invoices 都包含名為的列發票ID。在查詢中檢索 InvoiceID 時,SQL Server 會混淆從哪個資料表檢索資料。
要解決這種歧義,您必須為引用的每個欄位指定表格名稱。在這種情況下,您可以如下更新查詢:
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
透過指定 Invoices.InvoiceID,您明確告訴 SQL Server 您想要從 Invoices 表中擷取 InvoiceID 值。這消除了歧義並允許查詢正確執行。
或者,您可以使用表格別名為每個表格指派唯一識別碼。例如,您可以將Invoices 別名為Inv,將InvoiceLineItems 別名為ILI,並相應地更新查詢:
SELECT VendorName, Inv.InvoiceID, InvoiceSequence, InvoiceLineItemAmount FROM Vendors AS V JOIN Invoices AS Inv ON (V.VendorID = Inv.VendorID) JOIN InvoiceLineItems AS ILI ON (Inv.InvoiceID = ILI.InvoiceID) WHERE Inv.InvoiceID IN (SELECT InvoiceSequence FROM ILI WHERE InvoiceSequence > 1) ORDER BY VendorName, Inv.InvoiceID, InvoiceSequence, InvoiceLineItemAmount
使用表別名提供了另一種方法來解決列名歧義並確保查詢返回正確的結果。
以上是如何解決 SQL 連線中不明確的列名?的詳細內容。更多資訊請關注PHP中文網其他相關文章!