假设 active 是一个“布尔字段”(小整数,0 或 1)
# Find all active users
select * from users where active
# Find all inactive users
select * from users where NOT active
换句话说,“NOT”运算符可以直接应用于布尔字段吗?
假设 active 是一个“布尔字段”(小整数,0 或 1)
# Find all active users
select * from users where active
# Find all inactive users
select * from users where NOT active
换句话说,“NOT”运算符可以直接应用于布尔字段吗?
SQL 中的布尔值是一个位字段。这意味着 1 或 0。正确的语法是:
select * from users where active = 1 /* All Active Users */
或者
select * from users where active = 0 /* All Inactive Users */
使用 Postgres,您可以使用
select * from users where active
或者
select * from users where active = 't'
如果要使用整数值,则必须将其视为字符串。您不能使用整数值。
select * from users where active = 1 -- Does not work
select * from users where active = '1' -- Works
MS SQL 2008 也可以使用字符串版本的真假...
select * from users where active = 'true'
-- or --
select * from users where active = 'false'
在 SQL Server 中,您通常会使用。我不知道其他数据库引擎。
select * from users where active = 0
对于没有布尔值的本机类型的数据库,我个人更喜欢使用值为“Y”和“N”的 char(1)。字母比数字更易于用户使用,数字假定阅读它的人现在会认为 1 对应于真,0 对应于假。
'Y' 和 'N' 在使用 (N)Hibernate 时也能很好地映射。
PostgreSQL 支持布尔类型,因此您的 SQL 查询将在 PostgreSQL 中完美运行。
如果您使用 SQLite3 请注意:
它只需要't'或'f'。不是 1 或 0。不是 TRUE 或 FALSE。
刚学会了艰难的方法。