结构表显示here
如果我使用查询:
select idn
from balans as outerB WHERE idn!='' group by idn order by
ifnull((select sum(innerB.amount) from balans as innerB
where innerB.idn = outerB.idn
and status='up'), 0) -
ifnull((select sum(innerB.amount) from balans as innerB
where innerB.idn = outerB.idn
and status='down'), 0) desc
limit 15
我得到2行。
但是如果我添加条件>0
:
select idn from Balans as outerB WHERE idn!='' AND
(
(select sum(innerB.amount) from Balans as innerB
where innerB.idn = outerB.idn
and type='up') -
(select sum(innerB.amount) from Balans as innerB
where innerB.idn = outerB.idn
and type='down')
) > 0
group by idn order by
ifnull((select sum(innerB.amount) from Balans as innerB
where innerB.idn = outerB.idn
and type='up'), 0) -
ifnull((select sum(innerB.amount) from Balans as innerB
where innerB.idn = outerB.idn
and type='down'), 0) DESC
limit 15
结果我得到0行......
请告诉我哪里有错误?我为什么得到0行?
答案 0 :(得分:1)
您未在IFNULL()
条件中加入WHERE
。这就是你获得0行而不是2行的原因。子查询返回的总和是NULL
(这是SUM()
在没有匹配行时返回的内容,尽管人们可能认为{ {1}}更符合逻辑,它返回0
。)
这个附加条件,我将它放在NULL
子句中,而不是HAVING
(在这种情况下对结果没有影响,但它可能更有效):
WHERE
我没有理由用相关子查询编写此查询。您可以使用派生表和简单连接(还将select idn from Balans as outerB WHERE idn !=''
group by idn
HAVING
ifnull((select sum(innerB.amount) from Balans as innerB
where innerB.idn = outerB.idn
and type='up'), 0) -
ifnull((select sum(innerB.amount) from Balans as innerB
where innerB.idn = outerB.idn
and type='down'), 0) > 0
order by
ifnull((select sum(innerB.amount) from Balans as innerB
where innerB.idn = outerB.idn
and type='up'), 0) -
ifnull((select sum(innerB.amount) from Balans as innerB
where innerB.idn = outerB.idn
and type='down'), 0) DESC
limit 15 ;
更正为type
):
status
进行测试
答案 1 :(得分:0)
可能是因为
(select sum(innerB.amount) from Balans as innerB
where innerB.idn = outerB.idn
and type='up')
在所有情况下都不是一个数字,让MySQL感到困惑。
根据建议,我会添加 IFNULL(..)以防止MySQL认为你在非数字上做 - 。另一种选择是在(选择总和...)之前做 0 + ... ,这也应该告诉MySQL我们在这里谈论数字。