2017-04-13 40 views
0

我有兩個類似的表SQL到組類似的表的名字

表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   | 
+1

爲什麼你有相同的數據的兩個表?你爲什麼要標記MySql和SQL Server?哪一個?請同時分享您的查詢 – Raj

+0

如果您向table1添加(5,Mike,2000),預期結果如何? – jarlh

+0

@Raj抱歉它的MySQL。這兩個表是相似但不相同,但我需要顯示從兩個表 – user2666633

回答

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

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 
0

MySql不支持FULL OUTER JOIN。
但它支持左右&右連接和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