MySQL數據庫多表之間的查詢
問題描述
問題解答
回答1:思路一分兩種情況選出符合要求的company_id并union
把這些company_id的earning求和(2013-2014)
連接上company_name
好像搞的比較復雜。
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作為表的兩個field,SQL的邏輯會清晰很多:
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:
好復雜哦,同問,這樣的sql怎么寫,我在想是不是可以寫個存儲過程,畢竟存儲過程處理這樣復雜的邏輯容易一點
相關文章:
1. javascript - npm下載的模塊不完整是什么問題?2. java - Spring事務回滾問題3. mysql 聯表查詢4. apache - 想把之前寫的單機版 windows 軟件改成網絡版,讓每個用戶可以注冊并登錄。類似 qq 的登陸,怎么架設服務器呢?5. node.js - 我想讓最后進入數據庫的數據,在前臺最先展示,如何做到?6. MySQL數據庫服務器循環插入執行速度慢7. 剛放到服務器的項目出現這中錯誤,有高手指點嗎8. wordpress - Nginx中禁止訪問txt,robots.txt文件例外,規則該怎么寫?9. python 操作mysql如何經量防止自己的程序在之后被惡意注入(說白了就是問一下python防注入的一些要點)10. mysql - 面試題:如何把login_log表轉換成last_login表?
