MySQL数据库多表之间的查询
天蓬老师
天蓬老师 2017-04-17 15:49:58
[MySQL讨论组]
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(2)
ringa_lee

思路一

  1. 分两种情况选出符合要求的company_idunion

  2. 把这些company_idearning求和(2013-2014)

  3. 连接上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.earning
from cid_earning c left join tableA a using(id)

思路二

如果把2013和2014年的earning作为表的两个field,SQL的逻辑会清晰很多:

with
e3(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 earning
from e3 inner join e4 using(id)
        left join tableA a using(id)
where e4.earning > 20 or e3.earning + e4.earning > 50
伊谢尔伦

好复杂哦,同问,这样的sql怎么写,我在想是不是可以写个存储过程,毕竟存储过程处理这样复杂的逻辑容易一点

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号