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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8506379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 22:01:55  来源:igfitidea点击:

How to implement ternary conditional operator in MySQL

mysqlconditional-operator

提问by user1086355

I want to implement ternary conditional operator in MySQL. I have a table in which one field id exist. Its value may be null. I want to display idin ternary conditional format like this:

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

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

Is it possible in MySQL?

在 MySQL 中可能吗?

回答by Dewasish Mitruka

Try this :

尝试这个 :

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

回答by Lightness Races in Orbit

The documentationis your friend; you should read it!

文档是你的朋友;你应该读一读!

It says:

它说:

IFNULL(expr1,expr2)

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

IFNULL(expr1,expr2)

如果expr1不是NULL,则IFNULL()返回expr1;否则返回 expr2

And then lots of examples. This is equivalent to using a ternary conditional with a comparison to NULLand 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.

然后是很多例子。这等效于使用一个三元条件语句,NULL并将比较对象作为第二个操作数;不会碰巧使用符号?:让您到达那里与任何事情都没有真正的相关性。

So, in your case:

所以,在你的情况下:

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

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

如果您迫切希望明确提供三个操作数(为什么?!),请切换到IF

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

回答by a'r

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

有两种方法可以实现与三元运算符相同的逻辑:

  1. Use the IFfunction, eg. IF(expression, true result, false result)
  2. Use the CASEexpression, eg.

    CASE WHEN expression THEN <true result> ELSE <false_result> END
    
  1. 使用该IF功能,例如。IF(expression, true result, false result)
  2. 使用CASE表达式,例如。

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

When you are checking for NULL then you can use the IFNULLor COALESCEfunctions, eg.

当您检查 NULL 时,您可以使用IFNULLCOALESCE函数,例如。

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