在 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)

更新於: 18-Dec-2019

109 次瀏覽

開啟你的 職業

完成課程即可獲得認證

開始
廣告