2

结构表在这里显示

如果我使用查询:

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 行?

4

2 回答 2

1

您没有IFNULL()WHERE条件中包含 。这就是你得到 0 行而不是 2 行的原因。由子查询返回的 Sums 是NULLSUM()当没有匹配的行时返回,尽管有人可能认为这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 ;

我看不出用相关子查询编写此查询的理由。您可以使用派生表和简单连接(也更正了typeinto status):

SELECT di.idn
FROM 
    ( SELECT idn
      FROM Balans
      GROUP BY idn
      HAVING idn > ''
    ) AS di
  LEFT JOIN
    ( SELECT idn, SUM(amount) AS up
      FROM Balans
      WHERE status = 'up'
      GROUP BY idn
    ) AS bu
      ON bu.idn = di.idn
  LEFT JOIN
    ( SELECT idn, SUM(amount) AS down
      FROM Balans
      WHERE status = 'down'
      GROUP BY idn
    ) AS bd 
      ON bd.idn = di.idn 
WHERE COALESCE(bu.up, 0) - COALESCE(bd.down, 0) > 0 ;

SQL-Fiddle进行测试

于 2013-07-01T09:03:18.823 回答
0

大概是因为

 (select sum(innerB.amount) from Balans as innerB 
  where innerB.idn = outerB.idn 
  and type='up')

不是在所有情况下都是一个数字,让 MySQL 感到困惑。

正如建议的那样,我会添加IFNULL(..)以防止 MySQL 认为您正在做-在非数字上。另一种选择是在(select sum...)之前执行0 + ...,这也应该告诉 MySQL 我们在这里讨论的是数字。

于 2013-07-01T09:04:37.233 回答