MySQL 不支持 a FULL OUTER JOIN
,所以你需要模拟它。
一种方法:
SELECT IFNULL(sr.category,ss.category) AS category
, IFNULL(s.total,0)-IFNULL(r.total,0) AS total
FROM (
SELECT cr.pcode
FROM rreturn cr
GROUP BY cr.pcode
UNION
SELECT cs.pcode
FROM rsales cs
GROUP BY cs.pcode
) c
LEFT
JOIN ( SELECT sr.pcode
, MAX(sr.category) AS category
, SUM(sr.total) AS total
FROM rreturn sr
GROUP BY sr.pcode
) r
ON r.pcode = c.pcode
LEFT
JOIN ( SELECT ss.pcode
, MAX(ss.category) AS category
, SUM(sr.total) AS total
FROM rsales ss
GROUP BY ss.pcode
) s
ON s.pcode = c.pcode
内联视图c
获取出现在 rsales 或 rreturn 中的所有 pcode 的完整列表。
然后内联视图r
从 rreturn 获取每个 pcode 的总数,并s
从rsales
.
然后我们可以使用一个LEFT JOIN
操作来匹配基于 pcode 的行。
(这不是返回指定结果集的唯一方法,只是一个示例。)