Ternary operation 是否像 C 或 C++ 一样在 MySQL 中存在?
对,让我们首先查看 C 或 C++ 语言中三元运算符的工作原理。
X=(X > 10 && ( X-Y) < 0) ?: X:(X-Y);
以下是 C 语言中的演示代码。之后,我们将检查 MySQL。C 代码如下所示 −
#include <stdio.h> int main() { int X; int Y; int result; printf("Enter the value for X:"); scanf("%d",&X); printf("Enter the value for Y:"); scanf("%d",&Y); result=( X > 1 && (X-Y) < 0) ? X: (X-Y); printf("The Result is=%d",result); return 0; }
C 代码的快照如下 −
以下是输出 −
MySQL 三元运算符的语法如下 −
select case when yourtableAliasName.yourColumnName1 > 1 AND (yourtableAliasName.yourColumnName1-yourtableAliasName.yourColumnName2) < 0 THEN 0 ELSE (yourtableAliasName.yourColumnName1-yourtableAliasName.yourColumnName2) END AS anyAliasName from yourTableName yourtableAliasName;
为了理解以上三元运算符语法,让我们创建一个表。创建表的查询如下 −
mysql> create table TernaryOperationDemo -> ( -> X int, -> Y int -> ); Query OK, 0 rows affected (0.61 sec)
使用 insert 命令向表中插入一些记录。查询如下 −
mysql> insert into TernaryOperationDemo values(10,5); Query OK, 1 row affected (0.14 sec) mysql> insert into TernaryOperationDemo values(5,15); Query OK, 1 row affected (0.16 sec) mysql> insert into TernaryOperationDemo values(20,15); Query OK, 1 row affected (0.15 sec) mysql> insert into TernaryOperationDemo values(15,25); Query OK, 1 row affected (0.13 sec) mysql> insert into TernaryOperationDemo values(10,-11); Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from TernaryOperationDemo;
以下是输出 −
+------+------+ | X | Y | +------+------+ | 10 | 5 | | 5 | 15 | | 20 | 15 | | 15 | 25 | | 10 | -11 | +------+------+ 5 rows in set (0.00 sec)
以下是三元运算符的查询 −
mysql> select case when tbl.X > 1 AND (tbl.X-tbl.Y) < 0 THEN 0 ELSE (tbl.X-tbl.Y) END AS Result from TernaryOperationDemo tbl;
以下是输出 −
+--------+ | Result | +--------+ | 5 | | 0 | | 5 | | 0 | | 21 | +--------+ 5 rows in set (0.00 sec)
广告