什么是正确的MySql FULL JOIN语法?

Md.*_*ain 2 mysql sql join

以下是我的两张桌子;我想要结果如第三张表所示。我如何在MySQL中做到这一点(假设FULL JOIN)?

table_sales

product_id    quantity    date
c001          20        2013-09-03
t008          30        2013-09-01
t008          20        2013-09-03
c001          90        2013-09-09
Run Code Online (Sandbox Code Playgroud)

table_returns

product_id    quantity    date
t008          40        2013-09-08
t008          30        2013-09-01
c001          10        2013-09-03
Run Code Online (Sandbox Code Playgroud)

我想要得到这样的结果:

product_id     sale_qty      return_qty        date
c001           20            10              2013-09-03
c001           90            -               2013-09-09
t008           30            30              2013-09-01
t008           20            -               2013-09-01
t008           -             40              2013-09-08
Run Code Online (Sandbox Code Playgroud)

Gor*_*off 5

我做a的首选方法full join是获取所有ID的列表,然后left join到该列表:

select driver.product_id, s.quantity as sale_qty, r.quantity as return_qty, driver.date
from (select product_id, date from table_sales
      union 
      select product_id, date from table_returns
     ) driver left join
     table_sales s
     on driver.product_id = s.product_id and driver.date = s.date left join
     table_returns r
     on driver.product_id = r.product_id and driver.date = r.date;
Run Code Online (Sandbox Code Playgroud)

我发现将unionin放在from子句中使查询更加方便。关于处理变量,公式和联接的逻辑只需包含一次。

是SQL Fiddle演示其工作原理的。