僅在 MySQL 表中更新單列並基於條件增加


我們先建立一個表格 -

mysql> create table DemoTable
(
   Name varchar(50),
   Score int
);
Query OK, 0 rows affected (1.02 sec)

使用 insert 命令在表格中插入一些記錄 -

mysql> insert into DemoTable values('Sam',45);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('Mike',28);
Query OK, 1 row affected (0.36 sec)
mysql> insert into DemoTable values('Carol',27);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('David',67);
Query OK, 1 row affected (0.19 sec)

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

mysql> select *from DemoTable;

將生成以下輸出 -

+-------+-------+
| Name  | Score |
+-------+-------+
| Sam   |    45 |
| Mike  |    28 |
| Carol |    27 |
| David |    67 |
+-------+-------+
4 rows in set (0.00 sec)

以下是僅更新單列並基於條件增加的查詢 -

mysql> update DemoTable set Score=Score+10 where Score < 30;
Query OK, 2 rows affected (0.22 sec)
Rows matched: 2 Changed: 2 Warnings: 0

讓我們再次查看錶格記錄 -

mysql> select *from DemoTable;

將生成以下輸出 -

+-------+-------+
| Name  | Score |
+-------+-------+
| Sam   |    45 |
| Mike  |    38 |
| Carol |    37 |
| David |    67 |
+-------+-------+
4 rows in set (0.00 sec)

更新於:2019 年 10 月 3 日

90 次瀏覽

開啟動態 職業

完成課程並獲得認證

開始
廣告
© . All rights reserved.