sql - MySQL query resulting in the substraction of the sum of 2 columns in different tables -


i have mysql db following tables:

products:

product_id | product_name      1     |     blaster      2     |     faser      3     |     bfg 

orders:

order_id | product_id | order_product_qnt     1    |     1      |        10     2    |     2      |        5     3    |     3      |        7     4    |     2      |        10 

sells:

sell_id | product_id | sel_product_qnt     1   |      2     |        5     2   |      1     |        1     3   |      3     |        2 

what want query lists products followed amount.

the result should be:

product_name | quantity bfg          |    5 blaster      |    9 faser        |    10 

following barnar's suggestion got piece of code:

select      products.product_name,     coalesce (sum(orders.order_product_qnt), 0) - coalesce (sum(sells.sells_product_qnt), 0) quantity      products left join      orders on products.product_id = orders.product_id left join      sells on products.product_id = sells.product_id group      products.product_name 

the query works returns wrong values.

for example, have product has 6 orders, , 1 sell, logic dictates 6-1=5, query gives me 4 result.

or 1 18 orders , 6 sells, returns 60 (should 12).

any advise appreciated.

maybe this?

select  product_name, orders_cnt - sales_cnt quantity (     select product_name,     sum(orders) orders_cnt,     sum(sales) sales_cnt     (         select products.product_name,         ifnull(orders.order_product_qnt, 0) orders,         ifnull(sells.sells_product_qnt,0) sales     products     left join orders on products.product_id = orders.product_id     left join sells on products.product_id = sells.product_id     ) t1 group product_name ) t2 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -