我在编写SQL查询时遇到问题

时间:2012-09-04 18:32:24

标签: php sql

我有这样的SQL查询...

SELECT c.clientid, c.clientname, c.billingdate, 
       (SELECT ifnull(sum(total), 0) 
          FROM invoice i
         WHERE i.client = c.clientid AND i.isdeleted = 0) -
       (SELECT ifnull(sum(p.amount), 0) 
          FROM payment p
         INNER JOIN invoice i ON p.invoice = i.invoiceid
         WHERE i.client = c.clientid and i.isdeleted = 0) as balance, 
        CASE c.isactive+0 WHEN '1' THEN 'Stop'
                                   ELSE 'Start' END as Active
FROM client c
ORDER BY clientname

这样可以正常工作而没有错误,但请注意这部分......

(SELECT ifnull(sum(total), 0) 
          FROM invoice i
         WHERE i.client = c.clientid AND i.isdeleted = 0) -(SELECT ifnull(sum(p.amount), 0) 
   FROM payment p
  INNER JOIN invoice i ON p.invoice = i.invoiceid
  WHERE i.client = c.clientid AND i.isdeleted = 0) as balance

我写了一个PHP脚本......

if($remaining < 0){
    $remaining = $row['total'];
}else{
    $remaining = $remaining + $row['total'];
}

我想要做的是将我在PHP中编写的内容合并到我的SQL查询中,但我之前从未使用if语句编写过SQL查询(如果允许的话)。如何将我的PHP脚本合并到我的SQL查询中?有什么建议吗?

2 个答案:

答案 0 :(得分:2)

没有if,但case允许你做同样的事情。您已在查询中使用case,因此我认为您知道它是如何工作的。 :)

答案 1 :(得分:1)

您可以包装结果并使用它。确保总数和剩余时间是结果的一部分。

SELECT tt.clientid, tt.clientname, tt.billingdate, tt.total, tt.remaining, tt.active 
  FROM (
            ... here goes all of your select but the the order by 
       ) tt
ORDER BY tt.clientid

使用该构造,您可以执行在PHP中执行的操作

SELECT tt.clientid, tt.clientname, tt.billingdate, tt.total, tt.active,
       CASE WHEN tt.remaining < 0 then tt.total
                                  else tt.remaining - tt.total
            END as remaining
  FROM (
            ... here goes all of your select make sure you select a total and a remaining
       ) tt
ORDER BY tt.clientid

所以你要做的就是创建一个临时视图。不确定您的数据模型,但我认为这看起来像这样

SELECT tt.clientid, tt.clientname, tt.billingdate, tt.total, tt.active,
       CASE WHEN tt.remaining < 0 then tt.total
                                  else tt.remaining - tt.total
            END as remaining
 FROM (
    SELECT c.clientid, c.clientname, c.billingdate, 
       (SELECT ifnull(sum(total), 0) 
          FROM invoice i
         WHERE i.client = c.clientid AND i.isdeleted = 0) as total,
       (SELECT ifnull(sum(total), 0) 
          FROM invoice i
         WHERE i.client = c.clientid AND i.isdeleted = 0) -
       (SELECT ifnull(sum(p.amount), 0) 
          FROM payment p
         INNER JOIN invoice i ON p.invoice = i.invoiceid
         WHERE i.client = c.clientid and i.isdeleted = 0) as remaining, 
        CASE c.isactive+0 WHEN '1' THEN 'Stop'
                                   ELSE 'Start' END as Active
      FROM client c
      ) TT
ORDER BY clientname