如何始终返回子查询结果?

时间:2012-12-30 07:41:19

标签: mysql sql select join

我知道这个问题很多,但无法弄清楚我是否应该使用COALESCE ifnull或其他内容。

我有以下查询:

 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.

3 个答案:

答案 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'

感谢您的协助!

答案 1 :(得分: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

答案 2 :(得分: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'