gpt4 book ai didi

mysql - 左外连接未将第二个表显示为空

转载 作者:行者123 更新时间:2023-11-29 18:36:41 24 4
gpt4 key购买 nike

表结构表1

account 
123
1234
12345
123456

table 2
account
123
1234
12345

我想在表 1 的帐户上返回表记录 123456,当它与表 2 不匹配时,为第 2 列返回 null

SQL
SELECT table1.account, table2.account
from table1
left outer join table2
on (table1.account= table2.account)

最佳答案

您的 where 语句明确要求使用 table2.dates = '19-jul-17' 提供非空

您应该修改查询以检查空值:

SELECT  
table1.account, table2.account
from table1
left outer join table2
on (table1.account= table2.account)
where
t1.dates='20170719'
and ( table2.account is NULL
or
table2.dates = '20170719'
)

这会匹配第一个表中具有特定日期的行,以及第二个表中具有 null 或特定日期的行。

注意日期文字。原始查询使用特定于区域设置的格式。在不使用该格式的区域设置中,这很容易失败。不要介意两位数年份。

另一方面,

YYYYMMDD 是明确的。

更新

删除 where 子句后,将按预期返回 NULL:

declare @table1 table (id int)

declare @table2 table (id int)

insert into @table1
values
(123 ),
(1234 ),
(12345 ),
(123456)

insert into @table2
values
(123 ),
(1234 ),
(12345)

SELECT t1.id, t2.id
from @table1 t1
left outer join @table2 t2
on (t1.id= t2.id)

返回

id     id
123 123
1234 1234
12345 12345
123456 NULL

如果问题是“如何获取不匹配的行”,答案是使用 WHERE tabl2.ID IS NULL

关于mysql - 左外连接未将第二个表显示为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45234625/

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