MySQL數(shù)據(jù)庫(kù)多表之間的查詢
問(wèn)題描述
問(wèn)題解答
回答1:思路一分兩種情況選出符合要求的company_id并union
把這些company_id的earning求和(2013-2014)
連接上company_name
好像搞的比較復(fù)雜。
with cid(id) as ( select company_id from tableB where year = 2014 and earning > 20 union select company_id from tableB where year in (2013, 2014) group by company_id having sum(earning) > 50), cid_earning(id, earning) as ( select company_id, sum(earning) from tableB where company_id in (select id from cid) and year in (2013, 2014) group by company_id)select a.company_name, c.earningfrom cid_earning c left join tableA a using(id)思路二
如果把2013和2014年的earning作為表的兩個(gè)field,SQL的邏輯會(huì)清晰很多:
withe3(id, earning) as ( select company_id, earning from tableB where year = 2013), e4(id, earning) as ( select company_id, earning from tableB where year = 2014)select a.company_name, e3.earning + e4.earning as earningfrom e3 inner join e4 using(id)left join tableA a using(id)where e4.earning > 20 or e3.earning + e4.earning > 50回答2:
好復(fù)雜哦,同問(wèn),這樣的sql怎么寫(xiě),我在想是不是可以寫(xiě)個(gè)存儲(chǔ)過(guò)程,畢竟存儲(chǔ)過(guò)程處理這樣復(fù)雜的邏輯容易一點(diǎn)
相關(guān)文章:
1. android - weex 項(xiàng)目createInstanceReferenceError: Vue is not defined2. javascript - 如圖,百度首頁(yè),查看源代碼為什么什么都沒(méi)有?3. 網(wǎng)頁(yè)爬蟲(chóng) - python requests爬蟲(chóng),如何post payload4. npm鏡像站全新上線5. html - 關(guān)于CSS實(shí)現(xiàn)border的0.5px設(shè)置?6. PHPExcel表格導(dǎo)入數(shù)據(jù)庫(kù)怎么導(dǎo)入7. android - 哪位大神知道java后臺(tái)的api接口的對(duì)象傳到前端后輸入日期報(bào)錯(cuò),是什么情況?求大神指點(diǎn)8. pdo 寫(xiě)入到數(shù)據(jù)庫(kù)的內(nèi)容為中文的時(shí)候?qū)懭雭y碼9. PHP類(lèi)封裝的插入數(shù)據(jù),總是插入不成功,返回false;10. vue2.0+webpack 如何使用bootstrap?
