[英]I cannot subtract two different tables when one of them is empty
I have 2 tables rsales
and rreturn
and I have this following code. 我有2个表
rsales
和rreturn
,我有以下代码。 It runs properly when both table have values, but the problem is that when one of them is empty or no data is stored, it doesn't display a result. 当两个表都具有值时,它可以正常运行,但是问题在于,当其中一个表为空或不存储任何数据时,它不显示结果。 Is there something wrong with my code?
我的代码有问题吗?
$result = mysql_query("SELECT category, (SELECT SUM(s.total)-SUM(r.total) FROM rsales AS s WHERE r.pcode=s.pcode) as total, r.pcode FROM rreturn AS r GROUP BY r.pcode;");
MySQL doesn't support a FULL OUTER JOIN
, so you need to emulate it. MySQL不支持
FULL OUTER JOIN
,因此您需要模拟它。
One way to do it: 一种方法:
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
The inline view c
gets a full list of all pcode that appear in either rsales or rreturn. 内联视图
c
获取出现在rsales或rreturn中的所有pcode的完整列表。
Then inline view r
gets a total for each pcode from rreturn, and s
does the same from rsales
. 然后,内联视图
r
从rreturn获得每个pcode的总数,而s
从rsales
获得相同的rsales
。
We can then use a LEFT JOIN
operation to match the rows based on pcode. 然后,我们可以使用
LEFT JOIN
操作来基于pcode匹配行。
(This isn't the only way to return the specified resultset, just one example.) (这不是返回指定结果集的唯一方法,仅是一个示例。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.