MySQL 如何更新布尔值?
您可以使用UPDATE命令更新布尔值。如果使用布尔数据类型,MySQL在内部将其转换为tinyint(1)。它可以使用true或false文字面值,其中true表示1到tinyint(1),false表示0到tinyint(1)。
语法如下 −
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)
阅读更多:MySQL 教程