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怎么寫,我在想是不是可以寫個(gè)存儲(chǔ)過(guò)程,畢竟存儲(chǔ)過(guò)程處理這樣復(fù)雜的邏輯容易一點(diǎn)
相關(guān)文章:
1. python的文件讀寫問(wèn)題?2. javascript - h5上的手機(jī)號(hào)默認(rèn)沒(méi)有識(shí)別3. mysql里的大表用mycat做水平拆分,是不是要先手動(dòng)分好,再配置mycat4. javascript - 圖片鏈接請(qǐng)求一直是pending狀態(tài),導(dǎo)致頁(yè)面崩潰,怎么解決?5. javascript - 關(guān)于圣杯布局的一點(diǎn)疑惑6. python - 獲取到的數(shù)據(jù)生成新的mysql表7. javascript - 請(qǐng)問(wèn) chrome 為什么會(huì)重復(fù)加載圖片資源?8. window下mysql中文亂碼怎么解決??9. javascript - jquery hide()方法無(wú)效10. 怎么用css截取字符?
