如何在 MySQL 中实现条件运算符

我想在 mySQL 中实现条件运算符。我有一个表,其中有一个字段 id。它的值可能为空。我想以这样的三值条件格式显示 id:

select id = id == null ? 0 : id;

在 MySQL 中可能吗?

54563 次浏览

The documentation is your friend; you should read it!

It says:

IFNULL(expr1,expr2)

If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2.

And then lots of examples. This is equivalent to using a ternary conditional with a comparison to NULL and the comparison subject as the second operand; that it doesn't happen to use the symbols ? and : to get you there is not really relevant to anything.

So, in your case:

SELECT IFNULL(`id`, 0) FROM `table`

If you're desperate to provide three operands explicitly (why?!), then switch to IF:

SELECT IF(`id` IS NULL, 0, `id`) FROM `table`

Try this :

select if(Id is null, 0, id) as Id;

There are two ways that you can implement the same logic as a ternary operator:

  1. Use the IF function, eg. IF(expression, true result, false result)
  2. Use the CASE expression, eg.

    CASE WHEN expression THEN <true result> ELSE <false_result> END
    

When you are checking for NULL then you can use the IFNULL or COALESCE functions, eg.

IFNULL(ID, 0)
COALESCE(ID, 0)