对于我的SQL,我是 little 很多生锈,这让我感到疯狂。在我看来,由于某种原因,简单的外部联接是不起作用的。
T1:
column1,column2
101,1
101,2
101,3
102,2 lt
T2:
column1,column2
1,一
2,两个
3,三
4,四
(其中t1.column2 - > t2.column1)
鉴于我正在寻找的数据集上面的表格将是:
101,一个
101,两个
101,三
101,null
102,null
102,两个
102,null
102,null
也许我在想它,我不知道。我试图为任何选择返回4行,在这个例子中t1.column1 = 101或t1.column1 = 102等。
答案 0 :(得分:3)
听起来你想要的是:
SELECT sq.column1,
CASE WHEN EXISTS
( SELECT 1
FROM t1
WHERE column1 = sq.column1
AND column2 = t2.column1
)
THEN t2.column2
END
FROM ( SELECT DISTINCT
column1
FROM t1
) sq
CROSS
JOIN t2
;
答案 1 :(得分:3)
SELECT
td.column1,
CASE WHEN t1.column2 IS NOT NULL THEN t2.column2 END AS column2
FROM (SELECT DISTINCT column1 FROM t1) AS td
CROSS JOIN t2
LEFT JOIN t1 ON t1.column1 = td.column1 AND t1.column2 = t2.column1
上述内容的变体(在评论中由ypercube建议):
SELECT
t1_d.column1,
t2_2.column2
FROM (SELECT DISTINCT column1 FROM t1) AS t1_d
CROSS JOIN t2
LEFT JOIN t1
INNER JOIN t2 AS t2_2 ON t1.column2 = t2_2.column1
ON t1.column1 = t1_d.column1 AND t1.column2 = t2.column1
答案 2 :(得分:1)
SELECT t1.column1, t2.column2
FROM t2 JOIN t1 ON t1.column2 = t2.column1
UNION
SELECT t2.column2 AS column1, NULL AS column2
FROM t2
WHERE NOT EXISTS ( SELECT *
FROM t1
WHERE t1.column2 = t2.column1 );
答案 3 :(得分:0)
SELECT
t1.column1, t2.column2
FROM t1
LEFT JOIN t2 ON t1.column2 = t2.column1
应该这样做吗?