以下是我的两张桌子;我希望结果如第三个表所示。我怎么能在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
答案 0 :(得分:5)
我执行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
子句中会使查询更方便。关于处理变量,公式和连接的逻辑只需要包含一次。
Here是证明它有效的SQL小提琴。
答案 1 :(得分:4)
MySQL缺乏对FULL OUTER JOIN的支持。
因此,如果您想在MySQL上模拟完全加入,请查看here。
这是一个非常有用的链接,描述了完整连接的解决方法
示例解决方法将类似于
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