SQL查询有时会起作用

时间:2012-04-25 15:07:13

标签: sql

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

我从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 

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

任何提示都将不胜感激。

由于

1 个答案:

答案 0 :(得分:2)

这样的事情会把前两个总数混为一谈。

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

对于没有匹配的行,这将返回null,因此您可能需要添加:

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

这可能是你问题的根源。