使用LEFT JOIN 统计左右存在的数据( 二 )


 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结果:
idnameaccountcollection_amountinvoice_amunt1腾讯130101腾讯220202百度130302百度24050总结

  • 企业分组统计收款和发票表,只需要对企业做group by分组即可 。
  • 企业和账套一起分组,left join只会统计左边存在的数据,而需要统计两边都存在的数据 。
    • 使用union多表查询比较繁琐 。
    • left join使用on 1 = 1查询不添加限制条件,查询所有公司的账套,再关联发票和收款 。
参考
  • sql left join on 条件不写可以吗 会怎么样
  • mysql中的几种join 及 full join,自然连接问题

经验总结扩展阅读