左联接:显示右侧的null

发布于 2025-01-28 06:03:09 字数 675 浏览 1 评论 0原文

假设我们有2列表

TABLEA           TABLEB

1                 1   01/03/2022
2                 2   01/01/2022
3

此SQL语句:

select id 
from tableA 
left join tableB on tableA.id = tableB.id

显示:

1       1 01/03/2022
2       2 01/01/2022
3       NUll

不幸的是,当我在右表上添加限制时,行为并不相同。

select id   
from tableA 
left join tableB on tableA.id = tableB.id
where tableB.date > '01/01/2022'

我想要这样的东西:

1      1 01/03/2022
2      NULL
3      NULL

但是我明白了:

1      1 01/03/2022

仅此而已。我没想到这种行为。有人可以告诉该查询应该是什么吗?

Let's say we have 2 tables

TABLEA           TABLEB

1                 1   01/03/2022
2                 2   01/01/2022
3

This SQL statement:

select id 
from tableA 
left join tableB on tableA.id = tableB.id

displays:

1       1 01/03/2022
2       2 01/01/2022
3       NUll

Unfortunately, when I add a restriction on the right table, the behaviour is not the same.

select id   
from tableA 
left join tableB on tableA.id = tableB.id
where tableB.date > '01/01/2022'

I would like something like this :

1      1 01/03/2022
2      NULL
3      NULL

But I get this:

1      1 01/03/2022

That's all. I was not expecting this behavior. Can someone tell what the query should be ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

停顿的约定 2025-02-04 06:03:09
 CREATE TABLE #TABLEA 
(
    ID tinyint
);

CREATE TABLE #TABLEB
(
    ID tinyint
    ,Date date
);

INSERT INTO #TABLEA
VALUES(1),(2),(3)

INSERT INTO #TABLEB
VALUES(1,'2022-03-01'),(2,'2022-01-01'),(3,NULL)


SELECT 
    *
FROM 
    #TABLEA t1
LEFT JOIN #TABLEB t2 ON t2.ID= t1.ID

AND t2.Date > '2022-01-01'

DROP TABLE
    #TABLEA
    ,#TABLEB;

当您添加Where子句时,您有效地将左联接更改为内部连接。将条件放在联接谓词中可以保持左联接。

 CREATE TABLE #TABLEA 
(
    ID tinyint
);

CREATE TABLE #TABLEB
(
    ID tinyint
    ,Date date
);

INSERT INTO #TABLEA
VALUES(1),(2),(3)

INSERT INTO #TABLEB
VALUES(1,'2022-03-01'),(2,'2022-01-01'),(3,NULL)


SELECT 
    *
FROM 
    #TABLEA t1
LEFT JOIN #TABLEB t2 ON t2.ID= t1.ID

AND t2.Date > '2022-01-01'

DROP TABLE
    #TABLEA
    ,#TABLEB;

When you added the WHERE clause you effectively changed the LEFT JOIN to an INNER JOIN. Putting the condition in the JOIN predicates keeps the LEFT JOIN as intended.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文