MySQL數(shù)據(jù)庫(kù)多表之間的查詢(xún)
問(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. 運(yùn)行python程序時(shí)出現(xiàn)“應(yīng)用程序發(fā)生異常”的內(nèi)存錯(cuò)誤?2. 在mac下出現(xiàn)了兩個(gè)docker環(huán)境3. 利用IPMI遠(yuǎn)程安裝centos報(bào)錯(cuò)!4. spring-mvc - spring-session-redis HttpSessionListener失效5. javascript - QQ第三方登錄的問(wèn)題6. 測(cè)試自動(dòng)化html元素選擇器元素ID或DataAttribute [關(guān)閉]7. javascript - node得到req不能得到boolean8. javascript - 最近用echarts做統(tǒng)計(jì)圖時(shí)遇到兩個(gè)問(wèn)題!!9. java - Spring boot 讀取 放在 jar 包外的,log4j 配置文件,系統(tǒng)有創(chuàng)建日志文件,不寫(xiě)入日志信息。10. javascript - 在 model里定義的 引用表模型時(shí),model為undefined。

網(wǎng)公網(wǎng)安備