未能获得正确的加入所需的结果

时间:2019-11-08 14:47:53

标签: mysql sql

我正在尝试运行SELECT,但未能获得所需的结果。我在四个表之间有一个JOIN(实际上,还有更多表,但其余的大多数是显示实际名称而不是产品和公司ID值)。

Product
- id_product
- model
- id_origin
- availability
- product_category
- id_chipset
- id_producttype

Stock
- id_product
- id_company
- stock_quantity
- on_the_way
- date_stock

Items
- id_order
- id_sell_out
- quantity
- price
- id_product

Orders
- id_sell_out
- date
- NF
- id_client
- id_company

我需要什么:一个视图,其中包含所有已售出或有库存的产品列(Product.id_product),库存数量(Stock.on_the_way和Stock.date_stock)和销售(Items.quantity)。这是我当前的脚本:

SELECT  Product.model AS Chipset,
    SUM(items.quantity) AS Sales,
    Stock.stock_quantity AS 'Stock', 
    Stock.on_the_way AS 'On the Way', 
    WEEKOFYEAR(orders.date) AS 'Date'
FROM Orders
    INNER JOIN Items ON Orders.id_sell_out = Items.id_sell_out
    INNER JOIN Product ON Items.id_product = Product.id_product
    RIGHT JOIN Stock ON Product.id_product = Stock.id_product AND Orders.id_company = Stock.id_company
GROUP BY Stock.id_company, Product.model, WEEKOFYEAR(orders.date), Stock.stock_quantity, Stock.on_the_way
ORDER BY Stock.id_company, Product.model;

我得到的只是已售出且有库存的产品的行。通过在库存表中使用RIGHT JOIN(而不是INNER JOIN),我是否应该从库存中获取所有条目以及与JOIN其余部分的交集?

如何修复此代码以获得所需的结果?

1 个答案:

答案 0 :(得分:2)

RIGHT JOIN显然是违反直觉的。我会重写您的查询以改为使用LEFT JOIN。您可以从Product表开始,然后输入Stock,然后在left joinItem上输入Order

SELECT  
    p.model AS Chipset,
    SUM(i.quantity) AS Sales,
    s.stock_quantity AS 'Stock', 
    s.on_the_way AS 'On the Way', 
    WEEKOFYEAR(p.date) AS 'Date'
FROM 
    Product p
    INNER JOIN Stock s 
        ON p.id_product = s.id_product
    LEFT JOIN Items i
        ON i.id_product = p.id_product 
    LEFT JOIN Orders o
        ON  o.id_company = s.id_company
        AND o.id_sell_out = i.id_sell_out
GROUP BY 
    s.id_company, 
    p.model, 
    WEEKOFYEAR(o.date), 
    s.stock_quantity, 
    s.on_the_way
ORDER BY s.id_company, p.model;

注意:表别名使查询更短且更易于理解。我相应地修改了您的查询。