mysql - Left Join 未给出预期结果

标签 mysql

在这种特定情况下,我需要有关 Left Join 的帮助。

表创建语句:

 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

最佳答案

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)

关于mysql - Left Join 未给出预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54500326/

相关文章:

java - 将特定用户保存的多个 url 插入数据库的最佳方法是什么?

mysql - 如何使用 SQL 获取丢失的月份?

具有固定宽度和 blob 列的 MySQL 表设计

php - Laravel Eloquent - 选择 MAX 与其他列

MySQL从满足条件的行开始选择行

MySQL 嵌套查询计数

php - 私信系统查询

返回查询子集的 mysql 比返回查询的超集慢

mysql - 如何创建带有插入的存储过程?

MySQL IF ELSE 条件