我有两张桌子:
declare @Table1 as table (id int, value CHAR(1))
declare @Table2 as table (id int, value CHAR(1))
INSERT @Table1
VALUES (1, 'A'),
(1, 'B'),
(3, 'A')
INSERT @Table2
VALUES(1, 'A'),
(1, 'C'),
(2, 'A')
我想加入这两个表,以便最后我能够产生这个结果:
id value id value
1 A 1 A
1 B NULL NULL
NULL NULL 1 C
我很抱歉没有充分的解释(我的意思是根本没有解释)。我在这里尝试做的是(类似的)为id列创建内部联接(我的意思是在“id”列上获取两个集合中常见的记录)然后查看值列并在里面比较它们这个共同集的边界。
我希望我可以描述一下我的目的。
答案 0 :(得分:2)
希望这会起作用
SELECT distinct t1_id as id, t1_value as value , t2_id as id , t2_value as value
FROM (SELECT t1.id as t1_id, t1.value as t1_value from @Table1 t1 INNER JOIN @Table2 t2 on t1.id = t2.id) as A
FULL OUTER JOIN
(SELECT t2.id as t2_id, t2.value as t2_value from @Table1 t1 INNER JOIN @Table2 t2 on t1.id = t2.id) as B
on A.t1_value = B.t2_value
ORDER BY t1_id desc
基本上,我正在做的是在内部集合的值列上外部连接内部集合(在id列上的内部联接)。
答案 1 :(得分:0)
我赢了什么?
SELECT c.id,c.value,d.id,d.value
FROM
@Table1 c
full join
@Table2 d
on c.id = d.id and c.value = d.value
WHERE exists
(
SELECT a.id
FROM
@Table1 a
INNER JOIN
@Table2 b
ON a.id = b.id and a.id = c.id or d.id = a.id
)
答案 2 :(得分:0)
您可以通过预过滤表格,使用full outer join
和执行此操作:
select a.id as a_id, a.value as a_value,
b.id as b_id, b.value as b_value
from (select *
from tablea a
where a.id = 1
) a full outer join
(select *
from tableb b
where b.id = 1
) b
on a.id = b.id and a.value = b.value;