MySQL中如何使用三个表进行FULL OUTER JOIN操作?
P粉852114752
2023-09-01 21:48:57
<p>考虑以下表:</p>
<pre class="lang-sql prettyprint-override"><code>create table `t1` (
`date` date,
`value` int
);
create table `t2` (
`date` date,
`value` int
);
create table `t3` (
`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);
insert into `t3` (`date`, `value`)
values ("2022-01-01", 1),
("2022-02-01", 2),
("2022-03-01", 3);
</code></pre>
<p><code>t1</code>表缺少<code>2022-02-01</code>日期,<code>t2</code>缺少<code>2022-03-01</code>,<code>t3</code>缺少<code>2022-04-01</code>。我想要将这三个表连接起来,产生以下结果:</p>
<pre class="brush:php;toolbar:false;">| t1.date | t1.value | t2.date | t2.value | t3.date | t3.value |
| | | | | | |
| 2022-01-01 | 1 | 2022-01-01 | 1 | 2022-01-01 | 1 |
| null | null | 2022-02-01 | 2 | 2022-02-01 | 2 |
| 2022-03-01 | 3 | null | null | 2022-03-01 | 3 |
| 2022-04-01 | 4 | 2022-04-01 | 4 | null | null |</pre>
<p>我知道如何在两个表之间进行<code>full outer join</code>,但是在三个或更多表之间,情况会更复杂。我尝试了像这样的查询,但没有产生我想要的结果:</p>
<pre class="lang-sql prettyprint-override"><code>select *
from `t1`
left join `t2` on `t2`.`date` = `t1`.`date`
left join `t3` on `t3`.`date` = `t2`.`date` or `t3`.`date` = `t1`.`date`
union
select *
from `t1`
right join `t2` on `t2`.`date` = `t1`.`date`
right join `t3` on `t3`.`date` = `t2`.`date` or `t3`.`date` = `t1`.`date`;
</code></pre></p>
你走在正确的轨道上,但你必须考虑所有的组合 - 3个表 - 4个联合子句。