这是在 SQL 中进行布尔测试的正确方法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/859762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 02:02:57  来源:igfitidea点击:

Is this the proper way to do boolean test in SQL?

sqlboolean-expression

提问by Eric

Assume active is a "boolean field" (tiny int, with 0 or 1)

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

# Find all active users
select * from users where active 

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

In words, can the "NOT" operator be applied directly on the boolean field?

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

回答by Jose Basilio

A boolean in SQL is a bit field. This means either 1 or 0. The correct syntax is:

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

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

or

或者

select * from users where active = 0 /* All Inactive Users */

回答by Luc M

With Postgres, you may use

使用 Postgres,您可以使用

select * from users where active

or

或者

select * from users where active = 't'

If you want to use integer value, you have to consider it as a string. You can't use integer value.

如果要使用整数值,则必须将其视为字符串。您不能使用整数值。

select * from users where active = 1   -- Does not work

select * from users where active = '1' -- Works 

回答by Scott Ivey

MS SQL 2008 can also use the string version of true or false...

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

select * from users where active = 'true'
-- or --
select * from users where active = 'false'

回答by Jonathan Allen

In SQL Server you would generally use. I don't know about other database engines.

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

select * from users where active = 0

回答by stili

I personally prefer using char(1) with values 'Y' and 'N' for databases that don't have a native type for boolean. Letters are more user frendly than numbers which assume that those reading it will now that 1 corresponds to true and 0 corresponds to false.

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

'Y' and 'N' also maps nicely when using (N)Hibernate.

使用 (N)Hibernate 时,'Y' 和 'N' 也可以很好地映射。

回答by Jordi Cabot

PostgreSQL supports boolean types, so your SQL query would work perfectly in PostgreSQL.

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

回答by alexandros84

If u r using SQLite3 beware:

如果您使用 SQLite3,请注意:

It takes only 't' or 'f'. Not 1 or 0. Not TRUE OR FALSE.

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

Just learned the hard way.

刚刚学会了艰难的方式。