MySQL中添加新列并根据的IF条件设置值
要基于条件设置值,请使用IF()方法。让我们首先创建一个表-
create table DemoTable -> ( -> Age int -> );
使用插入命令在表中插入一些记录-
insert into DemoTable values(19); insert into DemoTable values(16); insert into DemoTable values(17); insert into DemoTable values(22);
使用select语句显示表中的所有记录-
select *from DemoTable;
输出结果
这将产生以下输出-
+------+ | Age | +------+ | 19 | | 16 | | 17 | | 22 | +------+ 4 rows in set (0.00 sec)
以下是根据条件设置值的查询-
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)