如何使用 MySQL 中的 if 子句将学生成绩显示为新一列中的“及格”或“不及格”
我们先创建一个表 −
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(100), -> Subject varchar(100), -> Score int -> ); Query OK, 0 rows affected (0.94 sec)
使用插入命令在表中插入一些记录 −
mysql> insert into DemoTable(Name,Subject,Score) values('Chris','MySQL',80); Query OK, 1 row affected (0.32 sec) mysql> insert into DemoTable(Name,Subject,Score) values('Robert','MongoDB',45); Query OK, 1 row affected (0.62 sec) mysql> insert into DemoTable(Name,Subject,Score) values('Adam','Java',78); Query OK, 1 row affected (0.52 sec)
使用选择语句从表中显示所有记录 −
mysql> select *from DemoTable;
输出
这将产生以下输出 −
+----+--------+---------+-------+ | Id | Name | Subject | Score | +----+--------+---------+-------+ | 1 | Chris | MySQL | 80 | | 2 | Robert | MongoDB | 45 | | 3 | Adam | Java | 78 | +----+--------+---------+-------+ 3 rows in set (0.00 sec)
以下是使用 MySQL 中的 if 子句以“及格”或“不及格”形式显示结果的查询。
mysql> select Name,Subject,Score,if(Score > 75,"PASS","FAIL") AS Status from DemoTable;
输出
这将产生以下输出 −
+--------+---------+-------+--------+ | Name | Subject | Score | Status | +--------+---------+-------+--------+ | Chris | MySQL | 80 | PASS | | Robert | MongoDB | 45 | FAIL | | Adam | Java | 78 | PASS | +--------+---------+-------+--------+ 3 rows in set (0.00 sec)
广告