我在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中存在任何记录,则记录必须从表2中获取数据,如果表1中不存在用户ID,则仅从表2中获取数据。
答案 0 :(得分:0)
试试这个:
SELECT *
FROM table1
WHERE table1.userid NOT IN (select userid from table2)
UNION
SELECT *
FROM table2
答案 1 :(得分: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
答案 2 :(得分: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)
答案 3 :(得分:0)
试试这个
SELECT *
FROM table1
WHERE userid NOT IN (select userid from table2)
UNION
SELECT *
FROM table2