优化成mysql脚本,不使用full outer join;SELECT COALESCE(storage_in.in_date, storage_out.out_date) AS date, COALESCE(storage_in.product_name, storage_out.product_name) AS product_name, IFNULL(storage_in.quantity,0) AS IN_, IFNULL(storage_out.quantity,0) AS OUT_, SUM(IFNULL(storage_in.quantity,0) - IFNULL(storage_out.quantity,0)) OVER (PARTITION BY COALESCE(storage_in.in_date,storage_out.out_date), COALESCE(storage_in.product_name,storage_out.product_name) ORDER BY COALESCE(storage_in.in_date, storage_out.out_date)) AS END_ FROM storage_in FULL OUTER JOIN storage_out ON storage_in.product_name=storage_out.product_name AND storage_in.in_date = storage_out.out_date ORDER BY 1,2;
时间: 2024-02-29 13:53:27 浏览: 178
以下是将 FULL OUTER JOIN 转换为 MySQL 脚本的方法,使用 UNION 和 LEFT JOIN 和 RIGHT JOIN 组合:
```
SELECT COALESCE(storage_in.in_date, storage_out.out_date) AS date,
COALESCE(storage_in.product_name, storage_out.product_name) AS product_name,
IFNULL(storage_in.quantity, 0) AS IN_,
IFNULL(storage_out.quantity, 0) AS OUT_,
SUM(IFNULL(storage_in.quantity, 0) - IFNULL(storage_out.quantity, 0))
OVER (PARTITION BY COALESCE(storage_in.in_date, storage_out.out_date),
COALESCE(storage_in.product_name, storage_out.product_name)
ORDER BY COALESCE(storage_in.in_date, storage_out.out_date)) AS END_
FROM
(SELECT in_date, product_name, quantity FROM storage_in
UNION
SELECT out_date, product_name, 0 FROM storage_out) AS storage
LEFT JOIN storage_in ON storage.in_date = storage_in.in_date
AND storage.product_name = storage_in.product_name
LEFT JOIN storage_out ON storage.out_date = storage_out.out_date
AND storage.product_name = storage_out.product_name
ORDER BY 1, 2;
```
这个脚本使用 UNION 将 storage_in 和 storage_out 表中的数据组合起来,LEFT JOIN 和 RIGHT JOIN 分别连接 storage_in 和 storage_out 表,从而实现 FULL OUTER JOIN 的效果。
阅读全文