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. python - (初学者)代码运行不起来,求指导,谢谢!2. 为什么python中实例检查推荐使用isinstance而不是type?3. mysql里的大表用mycat做水平拆分,是不是要先手动分好,再配置mycat4. window下mysql中文乱码怎么解决??5. sass - gem install compass 使用淘宝 Ruby 安装失败,出现 4046. html5 - H5 SSE的本质是什么?7. javascript - h5上的手机号默认没有识别8. python - 获取到的数据生成新的mysql表9. python的文件读写问题?10. javascript - js 对中文进行MD5加密和python结果不一样。
