mysql没有内置的boolean数据类型。存储布尔值(true/false)的最佳方式是使用 tinyint(1) 类型。在该类型中,1 代表 true,0 代表 false。虽然可以使用 boolean 关键字,但mysql会将其自动转换为 tinyint(1)。
详细操作指南
建表定义
使用 tinyint(1) 或 boolean(会被自动转换)。
create table example (
id int primary key,
is_active tinyint(1) -- 推荐
-- or is_active boolean (会被转换成tinyint(1))
);
插入数据
直接使用 true/false 关键字,或数字 1/0。
insert into example (id, is_active) values (1, true); insert into example (id, is_active) values (2, 0);
查询数据
查询结果仍为数字0或1。
select * from example where is_active = 1; -- 查询为true的记录
关键点与注意事项
- 兼容性:
true和false是常量,分别等价于1和0。 - orm映射:在java (hibernate/mybatis) 中,
tinyint(1)通常映射为boolean类型,即1->true,0->false。 - 为什么是tinyint(1) :虽然
tinyint可以存储 -128 到 127,但tinyint(1)的设计初衷是为了明确表示这是一个布尔值字段。
到此这篇关于mysql存储boolean类型的操作指南的文章就介绍到这了,更多相关mysql存储boolean类型内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论