2012-12-30 82 views
2

我知道這個問題被問了很多,但無法弄清楚,如果我應該使用COALESCEifnull或別的東西。如何總是返回子查詢結果?

我有以下查詢:

select (amount- 
(select (sum(l.amount_sum)-sum(lr.reward)) as total 
from logs l 
join logs_rewards lr on l.id = lr.related_log_id 
where l.agent_id = '1')) 
as balance 
from logs_payments 
where agent_id = '1' 

現在的問題是,如果agent_idlogs_payments存在的查詢將不返回行,但我想它做的是反正返回的結果,但如果amounts不存在,將其設置爲0的子查詢

現在我已經想過查詢不同的表和剛剛加盟的結果是這樣的:

select (lp.amount- 
(select (sum(l.amount_sum)-sum(lr.reward)) as total 
from logs l 
join logs_rewards lr on l.id = lr.related_log_id 
where l.agent_id = '1')) 
as balance 
from agents a 
join logs_payments lp on lp.agent_id = a.id 
where a.id = '1' 

但這也沒有奏效。我應該採取什麼方法解決這個問題?

爲了明確這一點,我想這個查詢總是返回子查詢的量,因此,如果不存在量仍然返回結果,但計算它爲0

回答

1

嗯,我知道了使用JW的約LEFT JOIN評論工作和Saharsh的言論有關ifnull使用下面的代碼:

select ifnull(sum(lp.amount),0)- 
(select (sum(l.amount_sum)-sum(lr.reward)) as total 
from logs l 
join logs_rewards lr on l.id = lr.related_log_id 
where l.agent_id = '1') 
as balance 
from agents a 
left join logs_payments lp on lp.agent_id = a.id 
where a.id = '1' 

謝謝你們的幫助!

+0

好吧,我會,但你的答案和JW一樣有幫助,它指出了我的正確方向。你的代碼不起作用(即使我修復了你在那裏出現的語法錯誤),所以我沒有接受它,並會接受我自己的,對不起,再次感謝幫助! –

0

使用LEFT JOIN

SELECT a.amount - COALESCE(b.total, 0) as balance 
FROM logs_payments a 
     LEFT JOIN 
     (
      SELECT agent_id, sum(l.amount_sum) - sum(lr.reward) as total 
      FROM logs l 
        INNER JOIN logs_rewards lr 
         ON l.id = lr.related_log_id 
      GROUP BY agent_id 
     ) b ON a.agent_id = b.agent_id 
WHERE a.agent_id = 1 
+0

這仍然不會返回任何內容,因爲logs_payments不包含所需agent_id –

+0

的任何記錄,所以您的意思是您正在搜索特定的'agent_id',但如果該ID沒有記錄,則您希望顯示零而不是任何內容。對? –

+0

雅,但我得到它的工作,我忘了左加入。非常感謝JW! –

0

試試這個:

SELECT l.agent_id, IFNULL(lp.amount, 0) amt, l.total 
FROM (SELECT l.agent_id, (SUM(l.amount_sum) - SUM(lr.reward)) AS total 
     FROM logs l INNER JOIN logs_rewards lr ON l.id = lr.related_log_id 
     WHERE l.agent_id = '1') AS l 
LEFT jon log_payments lp ON l.agent_id =lp.agent_id 
WHERE l.agent_id = '1'