当第二个 table 在 WHERE 语句中时,SQL 左连接不返回所有结果
SQL left join is not returning all results when second table is in WHERE statement
我正在尝试将两个 table 连接在一起,其中第二个 table 可能没有相关记录。在这种情况下,我希望第一个 table 中的数据仍然显示。我可以使用 LEFT JOIN 来做到这一点,但我 运行 遇到的问题是我在 WHERE 语句中引用了第二个 table。
SELECT a.field1, a.field2, b.field2 from a
LEFT JOIN b ON a.id = b.id
WHERE a.field1 = "value" AND b.field1 = "value"
似乎因为我在 WHERE 语句中引用了 table b,所以我只获取了 table b 中有相关记录的记录。有没有办法在 WHERE 语句中仍然包含 table b,并且仍然包含 table a 中的 return 记录,即使 table b 中没有相关记录?
谢谢!
将 left join
ed table 上的条件移动到联接的 on
子句:
SELECT a.field1, a.field2, b.field2
FROM a
LEFT JOIN b ON a.id = b.id AND b.field1 = 'value'
WHERE a.field1 = 'value'
然后 LEFT JOIN
在 table b
中找不到匹配项 table a
的给定 id
,a
中的所有列=14=] 是 null
,因此 where
子句中无法满足条件 b.field1 = 'value'
- 因此整行都从结果集中删除。您希望将该条件绑定到 left join
。
第二个 table 的过滤器需要在 on
子句中:
SELECT a.field1, a.field2, b.field2
from a LEFT JOIN
a
ON a.id = b.id AND b.field1 = value
WHERE a.field1 = 'value' ;
如果它们在 WHERE
子句中,则外部连接变成内部连接,因为 NULL
比较失败。
我假设 b
实际上是在查询中的某处定义的——你过于简单化了。
第一个 table 上的过滤器保留在 WHERE
子句中。
当您将 where 子句放在 left joined table 上时,即 b
,left join 会隐式转换为 INNER JOIN
你可以做的是将b.field1 = "value"
移动到左连接语句
SELECT a.field1, a.field2, b.field2 from a
LEFT JOIN b ON a.id = b.id and b.field1 = "value"
WHERE a.field1 = "value"
我正在尝试将两个 table 连接在一起,其中第二个 table 可能没有相关记录。在这种情况下,我希望第一个 table 中的数据仍然显示。我可以使用 LEFT JOIN 来做到这一点,但我 运行 遇到的问题是我在 WHERE 语句中引用了第二个 table。
SELECT a.field1, a.field2, b.field2 from a
LEFT JOIN b ON a.id = b.id
WHERE a.field1 = "value" AND b.field1 = "value"
似乎因为我在 WHERE 语句中引用了 table b,所以我只获取了 table b 中有相关记录的记录。有没有办法在 WHERE 语句中仍然包含 table b,并且仍然包含 table a 中的 return 记录,即使 table b 中没有相关记录?
谢谢!
将 left join
ed table 上的条件移动到联接的 on
子句:
SELECT a.field1, a.field2, b.field2
FROM a
LEFT JOIN b ON a.id = b.id AND b.field1 = 'value'
WHERE a.field1 = 'value'
然后 LEFT JOIN
在 table b
中找不到匹配项 table a
的给定 id
,a
中的所有列=14=] 是 null
,因此 where
子句中无法满足条件 b.field1 = 'value'
- 因此整行都从结果集中删除。您希望将该条件绑定到 left join
。
第二个 table 的过滤器需要在 on
子句中:
SELECT a.field1, a.field2, b.field2
from a LEFT JOIN
a
ON a.id = b.id AND b.field1 = value
WHERE a.field1 = 'value' ;
如果它们在 WHERE
子句中,则外部连接变成内部连接,因为 NULL
比较失败。
我假设 b
实际上是在查询中的某处定义的——你过于简单化了。
第一个 table 上的过滤器保留在 WHERE
子句中。
当您将 where 子句放在 left joined table 上时,即 b
,left join 会隐式转换为 INNER JOIN
你可以做的是将b.field1 = "value"
移动到左连接语句
SELECT a.field1, a.field2, b.field2 from a
LEFT JOIN b ON a.id = b.id and b.field1 = "value"
WHERE a.field1 = "value"