表中的和然后用不同的表减去

时间:2017-09-29 16:21:35

标签: mysql

两周后尝试我无法写这个查询请帮帮我

NOTE
  TABLE 1 sum(quantity_box) group by id_p and id_w
  TABLE 2 sum(quantity_box) group by id_p and id_w
then
  TABLE1.sum(quantity_box)- TABLE2.sum(quantity_box) where id_p = id_p and id_w = id_w

表1)wherehouseproduct_add id = id_w

id | name
10 | warehouse1
20 | warehouse2

table2)wherehouse_products

id | id_w |id_p |quantity_box
1  |  10  | 2   |  10  
2  |  10  | 2   |  50  
3  |  20  | 3   |  100
4  |  20  | 1   |  20
5  |  20  | 1   |  10
6  |  10  | 1   |  10
7  |  10  | 3   |  10    

table3)wherehouse_products_sell

 id | id_w |id_p |quantity_box
 1  |  10  | 2   |  50  
 2  |  20  | 3   |  30
 3  |  20  | 1   |  20  

table4)产品

id_p | product_name
1    | snack
2    | watebottle
3    | headphone

我希望输出像

id_w | id_p  | product_name| total_quantity_box
10   | 1     | snack       |10
10   | 2     | watebottle  |10   
10   | 3     | headphone   |10

  id_w | id_p  | product_name| total_quantity_box
    20   | 1     | snack       |10
    20   | 2     | watebottle  |10   
    20   | 3     | headphone   |70

现在我用

select wp.id_w,
wp.id_p,
wp.quantity - wps.quantity total_quantity_box
from
(select id_w,id_p,sum(quantity_box) quantity from warehouse_products group by id_w,id_p) wp
join
(select id_w,id_p,sum(quantity_box) quantity from warehouse_products_sell group by id_w,id_p) wps
using(id_w,id_p)

1 个答案:

答案 0 :(得分:1)

您需要使用LEFT JOIN,这样您才能获得wherehouse_products_sell内不存在的产品的结果。

select wp.id_w, wp.id_p, p.product_name,
    wp.quantity - IFNULL(wps.quantity, 0) total_quantity_box
from
    (select id_w,id_p,sum(quantity_box) quantity from warehouse_products group by id_w,id_p) wp
left join
    (select id_w,id_p,sum(quantity_box) quantity from warehouse_products_sell group by id_w,id_p) wps
using(id_w,id_p)
join products AS p ON wp.id_p = p.id_p