如何更新 MySQL 中的布尔值?
mysqlmysqli database更新于 2025/4/26 7:40:17
您可以使用 UPDATE 命令更新布尔值。如果您使用 BOOLEAN 数据类型,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)
使用 insert 命令在表中插入一些记录。 查询语句如下 −
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 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

