Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

mysql - Using a Case Statement With IS NULL and IS NOT NULL

SELECT 
    userid, 
    userName,
    CASE userName
    WHEN (userName IS NULL) THEN 'was null'
        WHEN (userName IS NOT NULL) THEN 'was not null'
    END AS caseExpressionTest
FROM
    top_users

This does not give me the results I want. When the value is not null, I get 'was null', and when actually is null, I get an actual MYSQL NULL value. What I want is that when userName is null, return 'was null' and when userName is not null, return 'was not null'. What am I doing wrong here?

I am purposefully trying to do this with CASE expression, not an IF or IFNULL expression.
Using MYSQL 8.0.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are misusing the case expression. There are two forms. The form you want is:

(CASE WHEN userName IS NULL THEN 'was null'
      WHEN userName IS NOT NULL THEN 'was not null'
 END) AS caseExpressionTest

Note: There is no userName after the CASE.

This checks each condition stopping at the first.

MySQL interprets booleans as a valid value. So your version is either:

-- when userName is NULL
(CASE userName
    WHEN 0 THEN 'was null'
    WHEN 1 THEN 'was not null'
END AS caseExpressionTest

This will return NULL.

Or:

-- when userName is not NULL
(CASE userName
    WHEN 1 THEN 'was null'
    WHEN 0 THEN 'was not null'
END AS caseExpressionTest

Presumably, userName is a string. This will convert userName to an integer based on leading digits. If there are no leading digits, you get 0, which is why there is a match.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...