2017-04-15 45 views
0

不知道我是否完全正確地執行此操作,因爲這是我第一次使用外鍵復飛。MySQL使用外鍵加入四個表SELECT語句拒絕第三

我正試圖在四張桌子上做一個JOIN

  • inventory_detail_history
  • 出貨量

與這兩個持有外鍵

  • shipment_details(批發)
  • shipment_ids沿

我在shipment_detailsid字段上應用了外鍵約束。 這引用了我的shipment_ids表中的shipment_id列。

shipment_details有以下欄目:idQuantityPurchasedUnitCostFreightTotalCustomDutiesTotal

shipment_ids有以下欄目: idSKUshipment_id

的想法是通過向規範化我的數據庫的嘗試多個SKU到特定的shipment_id(或者,我想,相當於shipment_detailsid)。

上做兩個表inventory_detail_historyshipmentsINNER JOIN是沒有問題的:

SELECT Shipments.ListingSKU, Shipments.SKU, idh.Quantity, Shipments.OrderIdentifier, idh.Price, Shipments.SalesTax, Shipments.ShippingCharge, Shipments.ShipmentCost, idh.FinalValueFee, idh.PayPalFee 
FROM Inventory_detail_history AS idh 
INNER JOIN Shipments ON idh.OrderIdentifier = Shipments.OrderIdentifier 
WHERE Shipments.SKU = 'SKU-NAME'; 

這會產生這樣的輸出:

enter image description here

但現在我需要加入這個我shipment_details表參照shipment_details.idshipment_ids.shipment_id關係的SKU表。

我可以單獨做這個。

SELECT sd.PurchaseQuantity, sd.UnitCost, sd.FreightTotal, sd.CustomDutiesTotal, sids.SKU, sids.shipment_id 
FROM shipment_details AS sd 
INNER JOIN shipment_ids AS sids on sd.id = sids.shipment_id 
WHERE sids.SKU = 'SKU-NAME'; 

產生一個輸出像這樣:

enter image description here

但是,我需要把在一行上的所有信息。

到目前爲止,這是我的最佳拍攝。

SELECT Shipments.ListingSKU, Shipments.SKU, idh.Quantity, Shipments.OrderIdentifier, idh.Price, Shipments.SalesTax, Shipments.ShippingCharge, Shipments.ShipmentCost, idh.FinalValueFee, idh.PayPalFee, sd.PurchaseQuantity, sd.UnitCost, sd.FreightTotal, sd.CustomDutiesTotal, sids.SKU, sids.shipment_id 
FROM Inventory_detail_history AS idh 
INNER JOIN Shipments 
ON idh.OrderIdentifier = Shipments.OrderIdentifier 
WHERE Shipments.SKU = 'SKU-NAME' 
INNER JOIN shipment_ids AS sids 
ON sids.SKU = 'SKU-NAME' 
INNER JOIN shipment_details AS sd 
ON sd.id = sids.shipment_id 

但我發現了一個錯誤

#1054 - 未知列「SD。「在‘​​字段列表’

注意,該欄是無關緊要的PurchaseQuantity,它只是拒絕第三個表中選擇。 如果我將其更改爲SELECT . . . . idh.PayPalFee, sd.UnitCost, sd.PurchaseQuantity

它會說#1054 - Unknown column 'sd.UnitCost' in 'field list'

任何幫助,提示有人能提供獲得適當的迴應?

回答

0

在查詢的末尾應用where子句,而不是在第二次連接之後應該解決該錯誤。

+0

你是對的,哈哈。我很親密,所以這很好。謝謝:) – bbruman

+0

很高興我能幫忙。請將答案標記爲正確:) – gaganshera