0

我有两张桌子:

id
1
2
3
4

t1 和 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

PS:是的,我确实意识到所需的输出很古怪。

4

2 回答 2

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小提琴

于 2013-01-29T16:56:26.203 回答
-1
SELECT DISTINCT t1.id, t1_copy.id FROM t1
LEFT OUTER JOIN t2 ON t1.id = t2.id
WHERE t1.id = 1
于 2013-01-29T17:08:35.827 回答