简体   繁体   中英

Subtract two mysql tables with negative in no existent rows

Hello every one i have two tables called: cash_billings_returns_articles, cash_billings_bills_articles. I need to subtract this tables for example.

Table: cash_billings_returns_articles 在此处输入图片说明

Table: cash_billings_bills_articles 在此处输入图片说明

I need to return the subtract of cashbillingBRCarticle_total column, like this:

cashbilling_id  article_id  cashbillingBRCarticle_total
55              3564         0
55              1871         0
55              9134         0
55              950          0
55              4402         0
55              2156         0
55              2228         0
55              2017         -90
55              3397         0

These rows represents the billings articles, It need be compared with cashbilling_id and article_id for each subtraction.

Any ideas?

Try this solution

SELECT t.cashbilling_id AS cashbilling_id_bills,
       s.cashbilling_id AS cashbilling_id_returns,
       t.article_id,
       t.cashbillingBRCarticle_total - IFNULL(s.cashbillingBRCarticle_total, 0) AS diff
FROM cash_billings_bills_articles t
     LEFT OUTER JOIN cash_billings_returns_articles s ON t.cashbilling_id = s.cashbilling_id AND t.article_id = s.article_id

Try this

SELECT 
     t2.cashbilling_id,
     t2.cashbillingbill_id,
     t2.article_id,
     (t1.cashbillingBRCarticle_total - t2.cashbillingBRCarticle_total) cashbillingBRCarticle_total
     FROM table2 t2
     RIGHT JOIN table1 t1 ON t1.article_id = t2.article_id

Try this

 select r.cashbillilng_id, r.cashbillingbill_id, r.article_id, 
 r.cashbillingBRCarticle_total - b.cashbillingBRCarticle_total as cashbillingBRCarticle_total 
 from cash_billings_bills_articles b 
 left join cash_billings_returns_articles r 
 on r.article_id=b.article_id 

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