使用LEFT JOIN 統計左右存在的數據

最近做了一個數據模塊的統計 , 統計企業收款、發票相關的數據,開始統計是比較簡單,后面再拆分賬套統計就有點小復雜,本文做一個簡單的記錄 。
需求企業表企業表t_company有如下字段:標識id、企業名稱name:
idname1騰訊2百度收款表企業對應有收款表t_collection有如下字段:標識id、賬套account、企業idcompany_id、收款金額amount:
idaccountcompany_idamount11130221203123042240開票表開票表t_invoice有如下字段:標識id、賬套account、企業idcompany_id、發票金額amount:
idaccountcompany_idamount11110221203123042250匯總企業統計【使用LEFT JOIN 統計左右存在的數據】現在要做一個統計 , 統計企業收款金額,以及發票金額,需要將收款表和發票表將company_id做group up操作 。開票表也是做類似的操作,企業表和上面的結果做left join連接操作 , sql如下:
select tc.id,tc.name,tc2.amount as collection_amount,ti.amount as invoice_amunt from t_company tcleft join (  select company_id,sum(amount) as amount from t_collection group by company_id) tc2 on tc.id = tc2.company_idleft join (  select company_id,sum(amount) as amount from t_invoice group by company_id) ti on tc.id = ti.company_id查詢結果:
idnamecollection_amountinvoice_amunt1騰訊50302百度7080再分賬套做匯總(重點)在上面統計的基礎上 , 再拆分賬套統計 。
使用LEFT JOIN 統計左右存在的數據

文章插圖
收款表和發票表做賬套的拆分,和企業表做關聯:
select tc.id,tc.name,tc2.amount as collection_amount,ti.amount as invoice_amunt from t_company tcleft join (  select company_id,account,sum(amount) as amount from t_collection  group by company_id,account) tc2 on tc.id = tc2.company_idleft join (  select company_id,account,sum(amount) as amount from t_invoice  group by company_id,account) ti on tc.id = ti.company_id and tc2.account = ti.account首先是將收款表做賬套的拆分,然后關聯發票表的賬套拆分 ??此茮]有問題,但是left join返回左邊的所有記錄,以及右邊字段相等的數據 。
使用LEFT JOIN 統計左右存在的數據

文章插圖
這樣就有一個問題:
如果左邊表沒有的數據,右邊的表也不會查出來 。比如以上查詢收款表不存在的賬套,發票表存在賬套也不會查出來 。這就是left join的局限性 。
全表連接解決方案一:MySQL有left join、right join應該也有full join全表連接 。
但是MySQL是不支持full join全表連接 。
網上也有解決方案使用union替換full_join,思路是左表左連接右邊 , 左表右連接右邊,將上面的兩個結果union連接起來:
select * from t1 left join t2 on t1.id = t2.idunionselect * from t1 right join t2 on t1.id = t2.id;上面只是兩個表的關聯,如果三個表或者更多的關聯,寫起來就比較繁瑣了 。
全表連接解決方案二:全表連接就是一個沒有限制的左表連接,就是去掉on關聯條件,
要left join所有的賬套,首先要顯示全所有的賬套,企業表關聯賬套表 , 但是兩個表是沒有關聯的,需要去掉on后面的關聯條件,但是MySQL語法連接后面必須要加on , 將約束條件改成1 = 1即可:
 select tc.id,tc.name,ta.id as account from t_company tc left join t_account ta on 1 = 1idnameaccount1騰訊11騰訊22百度12百度2查詢出所有的公司賬套之后 , 再left join收款表和發票表:
select tc.id,tc.name,tc.account,tc2.amount as collection_amount,ti.amount as invoice_amunt from (select tc.id,tc.name,ta.id as account from t_company tc left join t_account ta on 1 = 1)tcleft join (  select company_id,account,sum(amount) as amount from t_collection group by company_id,account) tc2 on tc.id = tc2.company_id and tc.account = tc2.accountleft join (  select company_id,account,sum(amount) as amount from t_invoice group by company_id,account) ti on tc.id = ti.company_id and tc.account = ti.account

推薦閱讀