2012-09-18 3 views
0

잔액 열에 where 절을 사용하여 아래 쿼리의 데이터를 필터링하는 방법. 어디 조건에서 균형을 사용할 때 [알 수없는 열 "잔액"의 "where 절"] 오류가 나타납니다. 발견 일치 지불 기록이없는 경우Where 절을 사용하여 조인 된 mysql 테이블의 데이터 필터링

select *,(it.Total - p.Amount) as Balance 
from invoices i 
left outer join invoice_items it 
    on i.ID=it.InvoiceID 
left outer join payment p 
    on p.InvoiceID=it.InvoiceID 
where Balance!=0; 

또한이 대신 잔액 항목에서 null 값을 표시하는, 나는 invoice_items 테이블의 총 값이 필요합니다.

+0

'어디에서 (it.Total - p.Amount)! = 0;'작동해야합니다 : http://stackoverflow.com/questions/200200/can-you-use-an-alias-in-the-where- 절 -In-mysql – danihp

답변

1

where 절에 별칭을 사용할 수 없습니다.

where (it.Total - p.Amount) <> 0 

과 다른 부분

select 
    (case when p.PaymentId IS NULL 
    then it.Total 
    else 
    (it.Total - p.Amount) 
    end) 

나에 대한 재 작성

. COALESCE는 의미

select *,(it.Total - p.Amount) as Balance 
from invoices i 
left outer join invoice_items it 
    on i.ID=it.InvoiceID 
left outer join payment p 
    on p.InvoiceID=it.InvoiceID 
where (it.Total - p.Amount) <> 0; 

당신의 별칭을 사용할 수 없습니다 p.Amount가 null의 경우, 드디어

select i.*,(it.Total - COALESCE(p.Amount, 0)) as Balance 
from invoices i 
left outer join invoice_items it 
    on i.ID=it.InvoiceID 
left outer join payment p 
    on p.InvoiceID=it.InvoiceID 
where it.Total - COALESCE(p.Amount, 0) <> 0; 
+0

감사. 그것은 매력처럼 작동했습니다. – Uma

0

이가 시도 그렇지 p.Amount에게

select it.Total - COALESCE(p.Amount, 0) 

을 사용하여 0을 사용 절은 시간순으로 실행되기 때문에 항상 SELECT 전에 발생합니다. SELECT는 항상 실행 체인의 마지막 단계입니다.

관련 문제