3

MySQL数据库(29):流程结构 if while

 1 year ago
source link: https://blog.51cto.com/u_13567403/5380002
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

流程结构 if while

两种基本用法

1、用在select查询中

if(条件, 结果为真, 结果为假);
mysql> select * from my_student;
+----+-----------+----------+------+--------+
| id | name      | class_id | age  | gender |
+----+-----------+----------+------+--------+
|  1 | 刘备      |        1 |   18 |      2 |
|  2 | 李四      |        1 |   19 |      1 |
|  3 | 王五      |     NULL |   20 |      2 |
|  4 | 张飞      |     NULL |   21 |      1 |
|  5 | 关羽      |     NULL |   22 |      2 |
|  6 | 曹操      |        1 |   20 |   NULL |
| 10 | 司马懿    |        6 |   26 |      1 |
+----+-----------+----------+------+--------+

mysql> select *, if(age > 20, '符合', '不符合') as result from my_student;
+----+-----------+----------+------+--------+-----------+
| id | name      | class_id | age  | gender | result    |
+----+-----------+----------+------+--------+-----------+
|  1 | 刘备      |        1 |   18 |      2 | 不符合    |
|  2 | 李四      |        1 |   19 |      1 | 不符合    |
|  3 | 王五      |     NULL |   20 |      2 | 不符合    |
|  4 | 张飞      |     NULL |   21 |      1 | 符合      |
|  5 | 关羽      |     NULL |   22 |      2 | 符合      |
|  6 | 曹操      |        1 |   20 |   NULL | 不符合    |
| 10 | 司马懿    |        6 |   26 |      1 | 符合      |
+----+-----------+----------+------+--------+-----------+
7 rows in set (0.00 sec)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK