在 MySQL 中如何添加新列并在符合条件时设置具体值?
要根据条件设置值,请使用 IF() 方法。我们首先创建一个表 −
mysql> create table DemoTable -> ( -> Age int -> ); Query OK, 0 rows affected (0.55 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values(19); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(16); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(17); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(22); Query OK, 1 row affected (0.19 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
输出
这将产生以下输出 −
+------+ | Age | +------+ | 19 | | 16 | | 17 | | 22 | +------+ 4 rows in set (0.00 sec)
以下是根据条件设置值的查询 −
mysql> select Age,if(Age > 18,'You are qualified!','Sorry, you are rejected!') AS Result from DemoTable;
输出
这将产生以下输出 −
+------+-------------------------+ | Age | Result | +------+-------------------------+ | 19 | You are qualified! | | 16 | Sorry, you are rejected!| | 17 | Sorry, you are rejected!| | 22 | You are qualified! | +------+-------------------------+ 4 rows in set (0.00 sec)
广告