MSSQL自己加入

时间:2013-01-29 16:52:05

标签: sql sql-server

我有两张桌子:

id
1
2
3
4

t1 AND t2

id | related_id
1  | 2
1  | 3

其中t2是t1记录之间的关系表。获得所需输出的最佳方法是什么?

t1.id | t1_copy.id
1     | NULL -- want to get this NULL row
1     | 2
1     | 3

简单JOIN几乎可以正常工作,但它不会给我第一行NULL

SELECT t1.id, t1_copy.id FROM t1
LEFT JOIN t2 ON t1.id = t2.id
LEFT JOIN t1 t1_copy ON t1_copy.id = t2.related_id
WHERE t1.id = 1
P.S:是的,我确实意识到所需的输出是古怪的。

2 个答案:

答案 0 :(得分:1)

看起来像一个简单的UNION应该做的伎俩

SELECT
   id, 
   null as copy_id
FROM
   t1 
WHERE
  exists (select * from t2 where t1.id = t2.id)
UNION ALL
SELECT
   t1.id,
   t2.related_id
FROM
   t1 
   INNER JOIN t2
   ON t1.id = t2.id

SQL Fiddle

答案 1 :(得分:-1)

SELECT DISTINCT t1.id, t1_copy.id FROM t1
LEFT OUTER JOIN t2 ON t1.id = t2.id
WHERE t1.id = 1