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. golang - 用IDE看docker源码时的小问题2. css - ul ol前边的标记如何调整样式呢3. docker images显示的镜像过多,狗眼被亮瞎了,怎么办?4. dockerfile - 为什么docker容器启动不了?5. 在windows下安装docker Toolbox 启动Docker Quickstart Terminal 失败!6. dockerfile - [docker build image失败- npm install]7. css - chrome浏览器input记录上次cookie信息后,有个黄色背景~如何去除!8. html - 爬虫时出现“DNS lookup failed”,打开网页却没问题,这是什么情况?9. mac连接阿里云docker集群,已经卡了2天了,求问?10. 用CSS3 box-sizing 属性实现两个并排的容器,如果想让容器中间有间隔该如何实现

网公网安备