我有两张相似的表
表1
| id | name | amount|
| 2 | Mike | 1000 |
| 3 | Dave | 2500 |
表2
| id | name | amount|
| 2 | Mike | 1200 |
| 4 | James| 2500 |
我想查询表格得到这样的结果:
| id | name | amount_table1| amount_table2|
| 2 | Mike | 1000 | 1200 |
| 3 | Dave | 2500 | |
| 4 | james| | 2500 |
答案 0 :(得分:2)
UNION ALL
表格。 GROUP BY
为每个ID /名称组合获取一行。
select id, name, sum(amount1), sum(amount2)
from
(
select id, name, amount as amount1, null as amount2 from table1
union all
select id, name, null, amount from table2
) dt
group by id, name
答案 1 :(得分:1)
你需要与左右连接结合
select a.id , a.name , a.amount amount_table1,b.amount amount_table2 from table1 a left join table2 b on (a.id=b.id)
union
select b.id , b.name ,a.amount,b.amount from table1 a right join table2 b on (a.id=b.id)
答案 2 :(得分:0)
MySql不支持FULL OUTER JOIN 但它支持LEFT& RIGHT加入和UNION。
select
t1.id, t1.name, t1.amount as amount_table1, t2.amount as amount_table2
from Table1 t1
left join Table2 t2 on t1.id = t2.id
union all
select t2.id, t2.name, t1.amount, t2.amount
from Table2 t2
left join Table1 t1 on t2.id = t1.id
where t1.id is null
第一个选择将只获得表1中的那些和两者中的那些 第二个选择将仅在表2中获得 并且UNION将这些结果集粘合在一起。
如果这是针对支持FULL JOIN的数据库,那么它将简化为:
select
coalesce(t1.id, t2.id) as id,
coalesce(t1.name, t2.name) as name,
t1.amount as amount_table1,
t2.amount as amount_table2
from Table1 t1
full join Table2 t2 on t1.id = t2.id