2

我知道这个问题被问了很多,但不知道我是否应该使用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_id中不存在logs_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。

4

3 回答 3

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'

谢谢两位的帮助!

于 2012-12-30T07:51:34.890 回答
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
于 2012-12-30T07:44:58.807 回答
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' 
于 2012-12-30T07:47:31.527 回答