将 TableA 的子集与 TableB 左连接,但保留 TableA 中的所有行

Left join a subset of TableA with TableB, but keeping all of the rows from TableA

我有两个 table,TableATableB,其中 TableB 有关于 TableA 行的额外数据,但仅当 [=15] =].如果我做类似

SELECT
    a.id,
    a.type,
    b.*
FROM TableA a
LEFT JOIN TableB b
ON a.id = b.id
    AND a.type IN (2, 3)
WHERE a.dt = '2022-02-03'
    AND b.dt = '2022-02-03'

它只会 return 行,其中 type 是 2 或 3。但是,我想 return 所有行 TableA,即使类型是't 2 或 3。当 type 不匹配时,我希望 b.* 中的列为 NULL

我想到的一个想法是将这个查询与一个单独的查询联合起来,该查询手动为 TableB 的所有列选择 null 并检查 type 是否不是 2 或 3 ,但这似乎很乏味。有没有更简洁的方法来完成此操作?

例如,TableA:

dt id type
'2022-02-03' 1 2
'2022-02-03' 2 3
'2022-02-03' 3 1
'2022-02-03' 1 1

TableB:

dt id col
'2022-02-03' 1 true
'2022-02-03' 2 false
'2022-02-03' 3 true

我的查询会 return 一个 table 喜欢

id type dt col
1 2 '2022-02-03' true
2 3 '2022-02-03' false

但我还想要 TableA 中的其余行

id type dt col
1 2 '2022-02-03' true
2 3 '2022-02-03' false
3 1 '2022-02-03' null
1 1 '2022-02-03' null

根据评论,问题是我在 WHERE 子句中放置了一些条件,而不是在连接条件中。如果我将查询修改为

SELECT
    b.*,
    a.dt,
    a.id,
    a.type
FROM TableA a
LEFT JOIN TableB b
ON a.id = b.id
    AND a.type IN (2, 3)
    AND a.dt = '2022-02-03'
    AND b.dt = '2022-02-03'

我得到了我想要的结果。