89

假设 active 是一个“布尔字段”(小整数,0 或 1)

# Find all active users
select * from users where active 

# Find all inactive users
select * from users where NOT active 

换句话说,“NOT”运算符可以直接应用于布尔字段吗?

4

7 回答 7

97

SQL 中的布尔值是一个位字段。这意味着 1 或 0。正确的语法是:

select * from users where active = 1 /* All Active Users */

或者

select * from users where active = 0 /* All Inactive Users */
于 2009-05-13T19:01:10.127 回答
30

使用 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 
于 2009-05-13T19:13:14.053 回答
14

MS SQL 2008 也可以使用字符串版本的真假...

select * from users where active = 'true'
-- or --
select * from users where active = 'false'
于 2009-05-13T19:08:05.187 回答
12

在 SQL Server 中,您通常会使用。我不知道其他数据库引擎。

select * from users where active = 0
于 2009-05-13T19:00:54.993 回答
3

对于没有布尔值的本机类型的数据库,我个人更喜欢使用值为“Y”和“N”的 char(1)。字母比数字更易于用户使用,数字假定阅读它的人现在会认为 1 对应于真,0 对应于假。

'Y' 和 'N' 在使用 (N)Hibernate 时也能很好地映射。

于 2009-05-13T19:30:52.793 回答
1

PostgreSQL 支持布尔类型,因此您的 SQL 查询将在 PostgreSQL 中完美运行。

于 2009-05-14T01:44:03.267 回答
-2

如果您使用 SQLite3 请注意:

它只需要't'或'f'。不是 1 或 0。不是 TRUE 或 FALSE。

刚学会了艰难的方法。

于 2017-03-01T03:09:08.360 回答