相当复杂但没有子查询
SELECT Table1.*
, CASE WHEN Table2.Field2 > 5 THEN Table2.Field1 ELSE NULL END
, CASE WHEN Table2.Field2 > 5 THEN Table2.Field2 ELSE NULL END
FROM Table1
FULL OUTER JOIN Table2 ON Table1.Field1 = Table2.Field1
WHERE COALESCE(Table2.Field2, 6) > 5
OR Table1.Field1 = Table2.Field1
测试脚本
;WITH Table1 AS (
SELECT * FROM (VALUES
(1, 1)
, (2, 2)
, (5, 5)
, (6, 6)
) AS Table1 (Field1, Field2)
)
, Table2 AS (
SELECT * FROM (VALUES
(1, 1)
, (3, 3)
, (4, 4)
, (5, 5)
, (7, 7)
) AS Table2 (Field1, Field2)
)
SELECT Table1.*
, CASE WHEN Table2.Field2 > 5 THEN Table2.Field1 ELSE NULL END
, CASE WHEN Table2.Field2 > 5 THEN Table2.Field2 ELSE NULL END
FROM Table1
FULL OUTER JOIN Table2 ON Table1.Field1 = Table2.Field1
WHERE COALESCE(Table2.Field2, 6) > 5
OR Table1.Field1 = Table2.Field1
结果
Field1 Field2 Field1 Field2
1 1 NULL NULL
5 5 NULL NULL
NULL NULL 7 7
6 6 NULL NULL
1 1 NULL NULL
2 2 NULL NULL