如果在 SQL 中的联接表之间未找到匹配项,则联接两个表并在结果集中显示 null
Join two tables and show null in result set if match not found between joined tables in SQL
我的 table 结构如下所示:
Table答:
AID AName
1 AAA
2 BBB
Table乙:
BID AID
10 1
10 2
11 2
在tableB中,AID是tableA主键的外键。BID 10属于AID 1和AID 2,BID 11只属于AID 2,不属于AID 1。我需要这样的结果:
预期结果:
BID AID AName
10 1 AAA
10 2 BBB
Null 1 AAA
11 2 BBB
Table A 是碱基 table。由于在table B中,对于BID 11,它没有AID 1的记录,所以新的结果集应该return NUll。
我无法使用连接来完成它。我怎样才能实现它?
您需要 TableA
的 CROSS
连接到 TableB
的不同 BID
以获得 AID
和 [=13= 的所有组合] 然后 LEFT
加入 TableB
:
SELECT b.BID, a.AID, a.AName
FROM TableA a CROSS JOIN (SELECT DISTINCT BID FROM TableB) t
LEFT JOIN TableB b ON b.BID = t.BID AND b.AID = a.AID
ORDER BY t.BID, a.AID
参见demo。
我的 table 结构如下所示:
Table答:
AID AName
1 AAA
2 BBB
Table乙:
BID AID
10 1
10 2
11 2
在tableB中,AID是tableA主键的外键。BID 10属于AID 1和AID 2,BID 11只属于AID 2,不属于AID 1。我需要这样的结果:
预期结果:
BID AID AName
10 1 AAA
10 2 BBB
Null 1 AAA
11 2 BBB
Table A 是碱基 table。由于在table B中,对于BID 11,它没有AID 1的记录,所以新的结果集应该return NUll。 我无法使用连接来完成它。我怎样才能实现它?
您需要 TableA
的 CROSS
连接到 TableB
的不同 BID
以获得 AID
和 [=13= 的所有组合] 然后 LEFT
加入 TableB
:
SELECT b.BID, a.AID, a.AName
FROM TableA a CROSS JOIN (SELECT DISTINCT BID FROM TableB) t
LEFT JOIN TableB b ON b.BID = t.BID AND b.AID = a.AID
ORDER BY t.BID, a.AID
参见demo。