2012-09-04 3 views
1

문제가 쓰는 내 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']; 
} 

나는 SQL의 한때를 쓴 적이없는 내가 내 SQL 쿼리 내 PHP에 쓴 통합되어 일을하려고하지만 있어요 전에 if 문으로 ery. 내 SQL 쿼리에 내 PHP 스크립트를 통합하는 방법은 무엇입니까? 어떤 제안?

+0

성능 측면에서 볼 때 데이터베이스에서 데이터를 가져 와서 'PHP'로 유효성 검사를 수행하는 것이 합리적이지 않습니까? – Phil

+0

그 문제는 내가 클라이언트의 목록을 반환하는 쿼리와 개별 나머지 잔액이 있으므로 각각의 클라이언트에 대해 ID를 얻고 각 클라이언트에 대해 PHP 스크립트를 실행해야한다는 것을 고려했습니다. – user1269625

+0

'$ remaining'과'$ row [ 'total']'이 쿼리와 어떤 관련이 있는지 모르겠다 ... – DaveRandom

답변

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 

은 그래서 당신이 할 것은 실제로 임시 뷰를 생성하는 것입니다

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 

PHP

에 당신은 당신이 무엇을 할 수있는 구성. 데이터 모델하지만 확실하지 그게 더 if 없다이

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 
2

처럼 보일 것이라고 생각하지만 거의 같은 수행 할 수 있습니다 case있다. 쿼리에 이미 case을 사용하고 있으므로 어떻게 작동하는지 알 것 같습니다. :)

관련 문제