MYSQL从多行组合两个表

时间:2015-10-15 07:00:48

标签: mysql vb.net

我有两个表,一个是所有产品,另一个是新购买产品。

产品表

Item    Qty
301       2
302       5
303       3
304       4
305       6

购买表

Item     Qty    Status    Date
302       5     used      09-15-2015
303       5     reserve   09-20-2015
301       5     used      09-20-2015
302       5     reserve   09-20-2015
304       5     used      10-15-2015
303       5     reserve   10-15-2015

我想显示产品表中的数量,并将purchases table的数量加入Product Table

这是我最初的SQL查询

SELECT product_name, product_quantity, quantity 
FROM products 
    LEFT OUTER JOIN purchases ON products.ID = purchases.product_ID 
WHERE product_status !='deleted' AND status != 'used'`. 

但是,它只返回保留的purchases table项目。

我想要实现的是

Item    Qty    Reserved Qty    Total
301       2     0                 2
302       5     5                 10
303       3     10                13
304       4     0                 4
305       6     0                 6

更新 新的SQL查询

SELECT product_name, product_quantity, p.quantity 
FROM products 
    LEFT OUTER JOIN (SELECT * FROM purchases 
        WHERE status = 'reserved' 
        GROUP BY product_ID) AS  p ON p.product_ID = products.ID 
WHERE products.product_status !='deleted'`

但它在保留的数量上返回0。

1 个答案:

答案 0 :(得分:0)

你的查询几乎就在那里,除了你需要总结保留项的数量然后使用GROUP BY,有点像这样

SELECT
    pd.item AS 'Item', pd.qty AS 'Qty', IFNULL(pr.reserved_quantity, 0) AS 'Reserved Qty', (pd.qty+IFNULL(pr.reserved_quantity, 0)) AS 'Total'
FROM
    product pd
    LEFT OUTER JOIN (SELECT item, SUM(qty) AS 'reserved_quantity' FROM purchases WHERE `status`='reserve' GROUP BY 1) AS pr ON pd.item=pr.item