在 MySQL 中使用 UPDATE 语句的 if 语句设置的条件显示记录
首先让我们创建一个表格 -
mysql> create table DemoTable -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20), -> StudentMarks int, -> Status varchar(20) -> ); Query OK, 0 rows affected (0.97 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable(StudentName,StudentMarks) values('Chris',79); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(StudentName,StudentMarks) values('David',59); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(StudentName,StudentMarks) values('Bob',60); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(StudentName,StudentMarks) values('Mike',45); Query OK, 1 row affected (0.16 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+-----------+-------------+--------------+--------+ | StudentId | StudentName | StudentMarks | Status | +-----------+-------------+--------------+--------+ | 1 | Chris | 79 | NULL | | 2 | David | 59 | NULL | | 3 | Bob | 60 | NULL | | 4 | Mike | 45 | NULL | +-----------+-------------+--------------+--------+ 4 rows in set (0.00 sec)
以下是更新时设置条件的查询 -
mysql> update DemoTable -> set Status=if(StudentMarks > 60 ,'PASS','FAIL'); Query OK, 4 rows affected (0.40 sec) Rows matched: 4 Changed: 4 Warnings: 0
让我们再次检查表记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+-----------+-------------+--------------+--------+ | StudentId | StudentName | StudentMarks | Status | +-----------+-------------+--------------+--------+ | 1 | Chris | 79 | PASS | | 2 | David | 59 | FAIL | | 3 | Bob | 60 | FAIL | | 4 | Mike | 45 | FAIL | +-----------+-------------+--------------+--------+ 4 rows in set (0.00 sec)
广告