2013-08-29 119 views
1

我有2個表具有相同的列。第一張桌子讓我存儲用戶賬單,第二張桌子存儲賬單取消。合併2個相同的錶行

first table 
----------- 
id - total 
----------- 
1 - 100 
2 - 85 
3 - 50 

second table 
----------- 
id - total 
----------- 
2 - 85 


Result of JOIN 
------------------------ 
id - total - status 
------------------------ 
1 - 100 - OK 
2 - 85 - OK 
3 - 50 - OK 
2 - 85 - CANCEL 

我該如何獲得上述結果?

回答

3

使用集合運算符UNION ALL將兩個表合併成一個表。

SELECT id, total, 'OK' as status 
FROM First_Table 
UNION ALL 
SELECT id, total, 'CANCEL' as status 
FROM Second_Table 
3

查詢:

SQLFIDDLEExample

SELECT t1.id, 
     t1.total, 
     'OK' AS status 
FROM first t1 
UNION ALL 
SELECT t2.id, 
     t2.total, 
     'CANCEL' AS status 
FROM second t2 

結果:

| ID | TOTAL | STATUS | 
-----|-------|--------| 
| 1 | 100 |  OK | 
| 2 | 85 |  OK | 
| 3 | 50 |  OK | 
| 2 | 85 | CANCEL | 
3

您可以使用下面的代碼:

select *, 'OK' AS [Status] from [first table] 
UNION ALL 
select *, 'Cancel' from [second table]