0

我有这个查询,它似乎大部分时间都在工作,但是当我知道它应该返回一些东西时,我仍然得到 NULL,

我从 开始select,然后这个

(select sum(total) from orders
        where customer = 9
        and iscredit = 1
        and isdeleted = false and not id = 1560)

这种代码和平让我获得了客户 9 的订单总数,而不是当前订单,就像以前的订单总数一样……还请注意 iscredit = 1 表示这些是信用订单。

接下来我要添加这个查询

(select sum(total) from orders
        where customer = 9
        and iscredit = 0
        and isdeleted = false and not id = 1560)

做同样的事情,但 iscredit 是 0 所以订单不是学分。

接下来我想减去此查询已支付的费用

- (select ifnull(sum(p.amount), 0) from payment p
        inner join orders o
        on p.order = o.id
        where o.customer = 9) as previous

所以所有这些都是我的查询的样子......

select 
(
    select sum(total) 
    from orders
    where customer = 9 and iscredit = 1 and isdeleted = false and not id = 1560
) 
+ 
(
    select sum(total) 
    from orders
    where customer = 9 and iscredit = 0 and isdeleted = false and not id = 1560
) 
- 
(
    select ifnull(sum(p.amount), 0) 
    from payment p
        inner join orders o
            on p.order = o.id
    where o.customer = 9
) as previous 

有没有更好的方法来写这个?

任何提示将不胜感激。

谢谢

4

1 回答 1

2

Something like this will lump the first two totals together.

(select sum(total)
from orders
where customer = 0
and (iscredit = 1 or iscredit = 0)
and isdeleted = false
and not id = 1560)

This will return null for no matching rows, so you might want to add:

(select ifnull(sum(total), 0)
from orders
where customer = 0
and (iscredit = 1 or iscredit = 0)
and isdeleted = false
and not id = 1560)

This is probably the source of your problems.

于 2012-04-25T15:11:33.687 回答