当其中一个表为空时,我无法减去两个不同的表

时间:2013-09-10 03:29:39

标签: php mysql

我有2个表rsalesrreturn,我有以下代码。当两个表都有值时,它可以正常运行,但问题是当其中一个表为空或没有存储数据时,它不会显示结果。我的代码有问题吗?

$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;");

1 个答案:

答案 0 :(得分:0)

MySQL不支持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的总计,srsales执行相同的操作。

然后我们可以使用LEFT JOIN操作来匹配基于pcode的行。

(这不是返回指定结果集的唯一方法,只是一个例子。)