从COALESCE中减去

时间:2013-04-01 13:12:33

标签: mysql sql

我有一个SQL查询,看起来像这样:

SELECT 
COALESCE(field1, 0) AS field1, 
COALESCE(field2, 0) AS field2,
COALESCE(field3 - field1 - field2, 0) AS field
FROM ...

However the problem with it is that given say:

field1 = 1
field2 = 0
field3 = 2

显示输出时,field3显示0,尽管2 - 1 - 0 = 1。

使用COALESCE,因为我左外连接几个表,这可能会导致Null值。

如果field3为null,我也会遇到任何问题吗?

谢谢

2 个答案:

答案 0 :(得分:5)

独立合并:

SELECT COALESCE(field1, 0) AS field1, COALESCE(field2, 0) AS field2,
       COALESCE(field3, 0) - coalesce(field1, 0) - coalesce(field2, 0) AS field
FROM ...

至于你的例子,我怀疑field2实际上是NULL而不是0。

答案 1 :(得分:1)

您无法使用同一级别上给出的别名进行计算。您需要再次重复该函数或将主计算包装在子查询中,

SELECT  field1, field2,
        field3 - (field1 + field2)
FROM
        (
            SELECT  COALESCE(field1, 0) AS field1, 
                    COALESCE(field2, 0) AS field2, 
                    COALESCE(field3, 0) field3
            FROM    TableName
        ) x

原因是因为SQL操作顺序如下:

  • FROM clause
  • WHERE子句
  • GROUP BY子句
  • HAVING条款
  • SELECT条款
  • ORDER BY子句

ALIASSELECT语句中提供,并且在创建它们的级别上无法访问。