[英]How to handle multiple JOIN and LEFT JOINS in MySQL
我有 5 個表需要連接。 這些表與客戶下的訂單以及訂單變成相關供應商的采購訂單有關。
product_sale
包含客戶訂購的產品。product
包含有關這些產品的主要信息。sale_purchase
是銷售訂單和采購訂單之間的橋接表。
product_purchase
包含采購訂單上的那些鏈接產品。grn
處理這些產品的接收。不幸的是,在客戶銷售訂單中,我需要訪問所有這些表中的信息。 這是我到目前為止的查詢:
SELECT
ps.*,
pp.received_qty,
p.group_ref,
p.subgroup_ref,
g.grn_id AS 'grn_ref',
g.grn_date
FROM
product_sale ps
INNER JOIN product p ON ps.product_ref = p.product_id
LEFT JOIN sale_purchase sp ON ps.sale_ref = sp.sale_ref
LEFT JOIN product_purchase pp ON pp.so_line_no = ps.line_no
LEFT JOIN grn g ON g.grn_id = pp.grn_ref
WHERE
ps.sale_ref = 150002
GROUP BY
line_no
ORDER BY
line_no
到目前為止一切順利,盡管一行的received_qty
是錯誤的:
第一行收到的數量應該是 7 而不是 4。我檢查了 grn 表,它肯定是 7。我可以就這個查詢哪里出錯得到一些幫助嗎? 對於 line_no 1.00,grn_ref 和 grn_date 也應該是 NULL
廢了伙計們。 我想到了。 我沒有考慮系統中的另一個采購訂單。 該問題的解決方案是將AND pp.purchase_ref = sp.purchase_ref
添加到 product_purchase 的左連接。 請參閱下面的修訂代碼:
SELECT
ps.*,
pp.received_qty,
p.group_ref,
p.subgroup_ref,
g.grn_id AS 'grn_ref',
g.grn_date
FROM
product_sale ps
INNER JOIN product p ON ps.product_ref = p.product_id
LEFT JOIN sale_purchase sp ON ps.sale_ref = sp.sale_ref
LEFT JOIN product_purchase pp ON pp.so_line_no = ps.line_no AND pp.purchase_ref = sp.purchase_ref
LEFT JOIN grn g ON g.grn_id = pp.grn_ref
WHERE
ps.sale_ref = 150002
GROUP BY
line_no
ORDER BY
line_no
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.