MySQL数据库多表之间的查询

我有两张表tableA和tableB

tableA

id company_name
1 AL
2 BD
3 TX
4 SY

tableB

id company_id year earning
1 1 2012 10
2 1 2013 40
3 1 2014 20
4 2 2013 10
5 2 2014 30
6 3 2013 20
7 3 2014 10
8 4 2012 20
9 4 2013 30
10 4 2014 30

说明:A表中的id对应B表中的company_id

要求说明:取出满足 (2013年+2014年)earning>50 或者 2014年earning>20 的公司

希望得到的查询是这样的

company_name earning(值为这个公司13年+14的收入)
AL 60
DB 50
SY 60

请问大家这个查询是怎么实现的呢?SQL语句该怎么写呢?

阅读 2.2k
2 个回答

思路一

  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怎么写,我在想是不是可以写个存储过程,毕竟存储过程处理这样复杂的逻辑容易一点

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题