左加入并没有给预期的结果

问题描述 投票:0回答:1

我需要帮助左中加入这种特殊情况下。

表创建语句:

 create temporary table `temp_table_A` ( `txn_dt` date not null, `id` int not null, `key` varchar(32) NOT NULL, `val` int NOT NULL, PRIMARY KEY (`txn_dt`, `id`));
 create temporary table `temp_table_B` ( `txn_dt` date not null, `id` int not null, `grade` varchar(32) NOT NULL ,  PRIMARY KEY (`txn_dt`, `id`));

人口数据的语句:

 insert into temp_table_A values ( 20190102,  1 , 'AA' , 10 );
 insert into temp_table_A values ( 20190102, 2 , 'BB' , 11 );
 insert into temp_table_A values ( 20190102, 3 , 'CC' , 12 );

 insert into temp_table_B values ( 20190103, 2 , 'CAT1');
 insert into temp_table_B values ( 20190103, 4 , 'CAT2'  );

查询被用来获取数据:

select key, val , grade
from 
    temp_table_A a
        LEFT JOIN
    temp_table_B b on a.id = b.id 
where a.txn_dt = 20190102 
and b.txn_dt = 20190103
and a.key = 'AA'

预期成绩 :

key           val        grade
----------   ----------  -------
AA           10          null

Actual results :
No rows returned
mysql
1个回答
0
投票

b.txn_dt为空。在b.txn_dt条件可以从结果集的预期结果。你需要

and (b.txn_dt = 20190103 or b.txn_dt is null)

我没有测试,但选择可能是对b.txn_id移动状态进入连接:

LEFT JOIN temp_table_B b on (a.id = b.id and b.txn_dt = 20190103)
© www.soinside.com 2019 - 2024. All rights reserved.