如何在 MySQL 中更新布林值?


你可以使用 UPDATE 命令更新布林值。如果你使用 BOOLEAN 資料型別,MySQL 會在內部將其轉換為 tinyint(1)。它可以採用真或假文字,其中真表示 tinyint(1) 的 1,假表示 tinyint(1) 的 0。

語法如下 −

UPDATE yourTableName SET yourColumnName = yourValue WHERE yourCondition;

為了理解上述語法,我們建立一個表。建立表的查詢如下 −

mysql> create table UpdateBooleans
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> isSuccessful BOOLEAN,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.55 sec)

使用插入命令在表中插入一些記錄。查詢如下 −

mysql> insert into UpdateBooleans(isSuccessful) values(true);
Query OK, 1 row affected (0.17 sec)

mysql> insert into UpdateBooleans(isSuccessful) values(false);
Query OK, 1 row affected (0.21 sec)

mysql> insert into UpdateBooleans(isSuccessful) values(true);
Query OK, 1 row affected (0.13 sec)

mysql> insert into UpdateBooleans(isSuccessful) values(false);
Query OK, 1 row affected (0.15 sec)

mysql> insert into UpdateBooleans(isSuccessful) values(false);
Query OK, 1 row affected (0.24 sec)

mysql> insert into UpdateBooleans(isSuccessful) values(false);
Query OK, 1 row affected (0.17 sec)

mysql> insert into UpdateBooleans(isSuccessful) values(true);
Query OK, 1 row affected (0.12 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下 −

mysql> select *from UpdateBooleans;

以下是輸出 −

+----+--------------+
| Id | isSuccessful |
+----+--------------+
| 1  | 1            |
| 2  | 0            |
| 3  | 1            |
| 4  | 0            |
| 5  | 0            |
| 6  | 0            |
| 7  | 1            |
+----+--------------+
7 rows in set (0.00 sec)

以下是更新布林值的查詢。我們來將所有 0 更新為 1

mysql> update UpdateBooleans set isSuccessful = true where isSuccessful = false;
Query OK, 4 rows affected (0.15 sec)
Rows matched: 4 Changed: 4 Warnings: 0

再次顯示錶中的記錄。查詢如下

mysql> select *from UpdateBooleans;

以下是輸出

+----+--------------+
| Id | isSuccessful |
+----+--------------+
| 1  | 1            |
| 2  | 1            |
| 3  | 1            |
| 4  | 1            |
| 5  | 1            |            
| 6  | 1            |
| 7  | 1            |
+----+--------------+
7 rows in set (0.00 sec)

更新於: 30-Jun-2020

13K+ 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

入門
廣告
© . All rights reserved.