Consider the following table:
create table `t1` ( `date` date, `value` int ); create table `t2` ( `date` date, `value` int ); insert into `t1` (`date`, `value`) values ("2022-01-01", 1), ("2022-03-01", 3), ("2022-04-01", 4); insert into `t2` (`date`, `value`) values ("2022-01-01", 1), ("2022-02-01", 2), ("2022-04-01", 4);
t1
table is missing 2022-02-01
date, t2
table is missing 2022-03-01
. I want to join these two tables to produce the following result:
| t1.date | t1.value | t2.date | t2.value | | | | | | | 2022-01-01 | 1 | 2022-01-01 | 1 | | null | null | 2022-02-01 | 2 | | 2022-03-01 | 3 | null | null | | 2022-04-01 | 4 | 2022-04-01 | 4 |
The solution is to use full connection:
select * from `t1` left join `t2` on `t2`.`date` = `t1`.`date` union select * from `t1` right join `t2` on `t2`.`date` = `t1`.`date`;
This can get the results I want. But using the where
statement breaks everything:
select * from `t1` left join `t2` on `t2`.`date` = `t1`.`date` where `t1`.`date` > "2022-01-01" union select * from `t1` right join `t2` on `t2`.`date` = `t1`.`date` where `t1`.`date` > "2022-01-01";
I expected to get this result:
| t1.date | t1.value | t2.date | t2.value | | | | | | | null | null | 2022-02-01 | 2 | | 2022-03-01 | 3 | null | null | | 2022-04-01 | 4 | 2022-04-01 | 4 |
But I got this result:
| t1.date | t1.value | t2.date | t2.value | | | | | | | 2022-03-01 | 3 | null | null | | 2022-04-01 | 4 | 2022-04-01 | 4 |
I know what's wrong but can't find a solution. The problem is that t1.date
> "whatever" filters out all empty rows in the t1
table. I've tried this method but it doesn't work:
where `t1`.`date` > "2022-01-01" or `t1`.`date` = null
You should use
"NULL = NULL" evaluates to false because NULL has no value. Therefore it cannot be the same as any other value (even another NULL). The correct way is to use
is null
It seems you should use
t2.date > "2022-01-01"
in the right join query.View the demo at https://dbfiddle.uk/reo8UanD.