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 - 请教如何获取百度贴吧新增的两个加密参数2. javascript - 使用百度文本编辑器ueditor不显示样式问题3. css3 - 关于css的问题,除了倒数第二个td 其他td的宽度都是15%;因为我表格字段数量不确定4. javascript - 能不能用js给一个div添加一个持续的hover的效果,就像有另一个鼠标一直放在上边?5. css - 使用blur()滤镜为什么有透明的效果6. docker - MySQL 报错:Access denied for user ’xxx’@’localhost’7. javascript - 给某个类添加一个伪类,这个类有click事件,现在我点击伪类也触发了click事件8. 如何用笔记本上的apache做微信开发的服务器9. python的 itchat微信api文档的 itchat.send如何发信息给指定用户?10. javascript - autocomplete ajax怎么配置,求教
