简体   繁体   中英

How to handle multiple JOIN and LEFT JOINS in MySQL

I have 5 tables that need to be joined. These tables have to do with orders placed by customers and the orders turned into purchase orders for the relevant suppliers.

  • Table product_sale holds the customers products that they've ordered.
  • Table product holds the main information on those products.
  • Table sale_purchase is a bridging table between the sale and purchase order.
    • Note: This may or may not exist as the product might be out of stock and no purchase order was required.
  • Table product_purchase holds those linked products on the purchase order.
  • Table grn handles the receiving of those products.

Unfortunately in the customers sales order, I will need to access information from all of these tables. Here's the query I have so far:

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

So far so good, although the received_qty for one line is wrong:

在此处输入图像描述

The first line's received qty should be 7 and not 4. I've checked the grn table and it definitely says 7. Can I please get some help as to where I am going wrong with this query? Also the grn_ref and grn_date should be NULL for line_no 1.00

Scrap it guys. I figured it out. I hadn't accounted for another purchase order that was in the system. Solution to the problem was adding AND pp.purchase_ref = sp.purchase_ref to the left join for product_purchase. See revised code below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM