3

以下是我的两张桌子;我想要第三个表中所示的结果。我如何在 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

table_returns

product_id    quantity    date
t008          40        2013-09-08
t008          30        2013-09-01
c001          10        2013-09-03

我想得到如下结果:

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
4

2 回答 2

6

我首选的方法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;

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

是证明它有效的 SQL Fiddle。

于 2013-09-08T14:28:59.403 回答
4

MySQL 缺乏对 FULL OUTER JOIN 的支持。

因此,如果您想在 MySQL 上模拟完全连接,请查看此处

这是一个非常有用的链接,描述了完全加入的解决方法

示例解决方法就像

SELECT  t_13.value AS val13, t_17.value AS val17
FROM    t_13
LEFT JOIN
t_17
ON      t_13.value = t_17.value
UNION ALL
SELECT  t_13.value AS val13, t_17.value AS val17
FROM    t_13
RIGHT JOIN
t_17
ON      t_13.value = t_17.value
WHERE   t_13.value IS NULL
ORDER BY
COALESCE(val13, val17)
LIMIT 30
于 2013-09-08T14:10:33.270 回答