如何在 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
How to implement ternary conditional operator in MySQL
提问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 notNULL,IFNULL()returnsexpr1; otherwise it returnsexpr2.
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:
有两种方法可以实现与三元运算符相同的逻辑:
- Use the
IFfunction, eg.IF(expression, true result, false result) Use the
CASEexpression, eg.CASE WHEN expression THEN <true result> ELSE <false_result> END
- 使用该
IF功能,例如。IF(expression, true result, false result) 使用
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 时,您可以使用IFNULL或COALESCE函数,例如。
IFNULL(ID, 0)
COALESCE(ID, 0)

![[Docker]:将 PHPMyAdmin 连接到 MySQL 不起作用](/res/img/loading.gif)