如何在 MySQL Insert 語句中新增 where 子句?


你需要為此使用 UPDATE 語句。

語法如下

update yourTableName
set yourColumnName1=yourValue1,yourColumnName2=yourValue2,....N
where yourCondition;

讓我們為我們的示例建立一個表

mysql> create table addWhereClauseDemo
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(30),
   -> StudentPassword varchar(40)
   -> );
Query OK, 0 rows affected (0.45 sec)

使用 insert 命令向表中插入一些記錄。

查詢如下

mysql> insert into addWhereClauseDemo(StudentName,StudentPassword) values('John','John123456');
Query OK, 1 row affected (0.14 sec)
mysql> insert into addWhereClauseDemo(StudentName,StudentPassword) values('Carol','99999');
Query OK, 1 row affected (0.24 sec)
mysql> insert into addWhereClauseDemo(StudentName,StudentPassword) values('Bob','OO7Bob');
Query OK, 1 row affected (0.16 sec)
mysql> insert into addWhereClauseDemo(StudentName,StudentPassword) values('David','David321');
Query OK, 1 row affected (0.26 sec)

使用 select 語句顯示錶中的所有記錄。

查詢如下

mysql> select *from addWhereClauseDemo;

輸出如下

+-----------+-------------+-----------------+
| StudentId | StudentName | StudentPassword |
+-----------+-------------+-----------------+
| 1         | John        | John123456      |
| 2         | Carol       | 99999           |
| 3         | Bob         | OO7Bob          |
| 4         | David       | David321        |
+-----------+-------------+-----------------+
4 rows in set (0.00 sec)

以下是如何新增 where 子句,即更新記錄的查詢

mysql> update addWhereClauseDemo
-> set StudentName='Maxwell',StudentPassword='Maxwell44444' where StudentId=4;
Query OK, 1 row affected (0.18 sec)
Rows matched: 1 Changed: 1 Warnings: 0

讓我們再次檢查表記錄。

查詢如下

mysql> select *from addWhereClauseDemo;

輸出如下

+-----------+-------------+-----------------+
| StudentId | StudentName | StudentPassword |
+-----------+-------------+-----------------+
| 1         | John        | John123456      |
| 2         | Carol       | 99999           |
| 3         | Bob         | OO7Bob          |
| 4         | Maxwell     | Maxwell44444    |
+-----------+-------------+-----------------+
4 rows in set (0.00 sec)

更新於: 30-Jul-2019

166 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始學習
廣告