简体   繁体   English

MySQL-为什么在null和if为null的情况下结果不同?

[英]MySQL - why different results between case when null and if is null?

I have a query like: 我有一个查询,如:

SELECT IF(b.field IS NULL, c.field, b.field) as `field`
FROM aaaaa a
LEFT OUTER JOIN bbbbb b
    ON b.uid = a.b_id
LEFT OUTER JOIN ccccc c
    ON c.uid = a.c_id;

this query works. 该查询有效。 my question is why does the previous query work when the following, using a CASE , does not: 我的问题是,为什么在以下情况下(使用CASE )不能执行先前的查询:

SELECT 
    CASE b.field 
        WHEN NULL THEN c.field
        ELSE b.field
    END as `field`
FROM aaaaa a
LEFT OUTER JOIN bbbbb b
    ON b.uid = a.b_id
LEFT OUTER JOIN ccccc c
    ON c.uid = a.c_id;

assume that either aaaaa.b_id or aaaaa.c_id will be null; 假设aaaaa.b_idaaaaa.c_id为null; never both and never neither. 永远不会,永远不会。 also assume foreign keys between aaaaa , bbbbb , and ccccc are all properly configured. 还假设aaaaabbbbbccccc之间的外键都已正确配置。 mysql v5.1.60 on rehl x86_64 在rehl x86_64上的mysql v5.1.60

the first query properly returned results as expected, but when i use the CASE , i am only returned the values for when the ELSE is satisfied (no c.field s return, only b.field s). 第一个查询正确返回的结果不如预期,但是当我使用CASE ,我只返回时的值ELSE满足(无c.field回归,只有b.field S)。 what gives? 是什么赋予了?

That's because that form of case checks the condition b.field = null , and you can't compare null values that way. 那是因为这种形式的case检查条件b.field = null ,并且您不能以这种方式比较null值。

Use this form of the case instead: 使用这种形式的case来代替:

CASE
    WHEN b.field IS NULL THEN c.field
    ELSE b.field
END as `field`

You can also use coalesce for this: 您还可以为此使用coalesce

COALESCE(b.field, c.field) as `field`

Or ifnull : ifnull

IFNULL(b.field, c.field) as `field`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM