search

Home  >  Q&A  >  body text

How to use three tables to perform FULL OUTER JOIN operation in MySQL?

<p>Consider the following table:</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>The table is missing<code>2022-02-01</code>date,<code>t2</code>is missing<code>2022-03-01< /code>, <code>t3</code> is missing <code>2022-04-01</code>. I want to join these three tables to produce the following result: </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>I know how to do a <code>full outer join</code> between two tables, but between three or more tables it's more complicated. I tried a query like this but it didn't produce the results I wanted: </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>
P粉852114752P粉852114752458 days ago535

reply all(1)I'll reply

  • P粉176203781

    P粉1762037812023-09-02 18:31:10

    You are on the right track, but you have to consider all combinations - 3 tables - 4 union clauses.

    -- t1与t2进行全连接
    select *
    from `t1`
    left join `t2` on `t2`.`date` = `t1`.`date` 
    union 
    select *
    from `t1`
    right join `t2` on `t2`.`date` = `t1`.`date` 
    
    -- t1与t3进行全连接
    union 
    select *
    from `t1`
    left join `t3` on `t3`.`date` = `t1`.`date` 
    
    union 
    select *
    from `t1`
    right join `t3` on `t3`.`date` = `t1`.`date`

    reply
    0
  • Cancelreply