gpt4 book ai didi

SQL left outer join 但检测哪些行是 "filled"with nulls

转载 作者:行者123 更新时间:2023-11-29 14:21:18 25 4
gpt4 key购买 nike

我有一个具有一对多关系的 SQL LEFT OUTER JOIN。这是一个例子

表A

+------+------+------+
| Col1 | Col2 | Col3 |
+------+------+------+
| a1 | a2 | a3 |
| b1 | b2 | b3 |
| c1 | c2 | c3 |
+------+------+------+

表B

+------+------+------+
| Col1 | Col2 | Col3 |
+------+------+------+
| x1 | a2 | NULL |
| y1 | b2 | y3 |
+------+------+------+

我在 Col2 上加入表格,所以:

SELECT * FROM tableA
LEFT OUTER JOIN tableB ON tableA.col2 = tableB.col2
WHERE tableB.col3 IS NOT NULL

此查询按预期返回表 A 的第二行。我的问题是我还需要 tableA 的第 3 行,因为它在 tableB 上没有相关记录。由于在未找到关联时 JOIN 子句用空值“填充”,因此查询不会返回该行。所以总而言之,我需要表 A 中的所有记录都与表 B 中的关联记录 AND tableB.col3 IS NOT NULL,以及表 B 中的所有记录在表 B 中没有关联的记录。

预期输出(我需要的):

+------+------+------+
| b1 | b2 | b3 |
| c1 | c2 | c3 |
+------+------+------+

关于如何检索它的任何想法?

感谢您的帮助!

最佳答案

我将问题解释为:

I need all records from table A that have an associated record from table B AND tableB.col3 IS NULL AND all records from table A that have no associated record on table B.

这有点更具挑战性。我认为以下查询实现了逻辑:

SELECT *
FROM tableA a LEFT JOIN
tableB b
ON a.col2 = b.col2
WHERE (a.col2 = b.col2 and b.col3 is null) or
(b.col2 is null)

编辑:

根据您的编辑,您似乎想要:

I need all records from table A that have an associated record from table B AND tableB.col3 IS NOT NULL AND all records from table A that have no associated record on table B.

SELECT *
FROM tableA a LEFT JOIN
tableB b
ON a.col2 = b.col2
WHERE (a.col2 = b.col2 and b.col3 is not null) or
(b.col2 is null)

关于SQL left outer join 但检测哪些行是 "filled"with nulls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25734407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com