2013-06-13 73 views
0

我在這樣的sql server中有兩個表。從sql server中的兩個表中提取記錄

表1

userid value 
a   1 
b   1 
c   1 
d   1 

表2

userid   value 
e    0 
f    0 
g    0 
a    0 
b    0 

欲像這樣輸出從以上兩個表

usrid   value 
a    0 
b    0 
c    1 
d    1 
e    0 
f    0 
g    0 

如果任何記錄存在於表1中,記錄必須是fe查詢表2中的數據,其他智能表1中的數據。如果用戶標識不存在於表1中並僅從表2獲取記錄。

+0

如果有用戶ID匹配,則從表2中獲取的值.. –

回答

0

試試這個:

SELECT * 
FROM table1 
WHERE table1.userid NOT IN (select userid from table2) 

UNION 

SELECT * 
FROM table2 
0

試試這個:

select ISNULL(t1.usrid,t2.usrid) as usrid 
     ,ISNULL(t1.value,t2.value) as value 
from table1 t1 
outer join table2 t2 on t1.usrid = t2.usrid 
0

試試這個

SELECT * FROM dbo.Table_2 AS t WHERE t.uid IN (SELECT t2.uid FROM dbo.Table_1 AS t2) 
UNION 
SELECT * FROM dbo.Table_1 AS t WHERE t.uid NOT IN (SELECT t2.uid FROM dbo.Table_2 AS t2) 
UNION 
SELECT * FROM dbo.Table_2 AS t WHERE t.uid NOT IN (SELECT t2.uid FROM dbo.Table_1 AS t2) 
0

試試這個

SELECT * 
FROM table1 
WHERE userid NOT IN (select userid from table2) 
UNION 
SELECT * 
FROM table2 
相關問題