MySQL数据库多表之间的查询
本文介绍了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语句该怎么写呢?
解决方案
思路一
分两种情况选出符合要求的
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.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
这篇关于MySQL数据库多表之间的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文