Postgresql数据库中布尔数据类型。
一、布尔类型
在Postgresql数据库中Boolean的值除了“true”(真)、“false”(假),还有一个“unknown”(未知)状态。
如果是unknown时用NULL表示。布尔类型在Postgresql中可以用不带引号的TRUE或FALSE表示,也可以用更多表示真和假的带引号的字符表示:
真 | 假 | 备注 |
---|---|---|
‘TRUE’ | ‘FALSE’ | |
tRue | fAlse | |
‘tRue’ | ‘fAlse’ | 不分大小写 |
‘t’ | ‘f’ | 单一字符表示 |
‘yes’ | ‘no’ | 英文的是和否表示 |
‘y’ | ‘n’ | yes和no的简写表示 |
‘1’ | ‘0’ | 1表示true,0表示false |
以上表格中值加引号都可以表示真和假,但是在Postgresql中Boolean类型字段里存储的值还是 t (true)和 f(false)。
测试:
postgres=# create table tb_boolean(id int,col1 boolean, col2 text);
CREATE TABLE
postgres=# insert into tb_boolean VALUES(1,TRUE,'TRUE');
INSERT 0 1
postgres=# insert into tb_boolean VALUES(1,FALSE,'FALSE');
INSERT 0 1
postgres=# insert into tb_boolean VALUES(1,tRue,'tRue');
INSERT 0 1
postgres=# insert into tb_boolean VALUES(2,fAlse,'fAlse');
INSERT 0 1
postgres=# insert into tb_boolean VALUES(3,'tRue','''tRue''');
INSERT 0 1
postgres=# insert into tb_boolean VALUES(4,'fAlse','''fAlse''');
INSERT 0 1
postgres=# insert into tb_boolean VALUES(7,'t','''t''');
INSERT 0 1
postgres=# insert into tb_boolean VALUES(8,'f','''f''');
INSERT 0 1
postgres=# insert into tb_boolean VALUES(9,'no','''no''');
INSERT 0 1
postgres=# insert into tb_boolean VALUES(10,'yes','''yes''');
INSERT 0 1
postgres=# insert into tb_boolean VALUES(11,'y','''y''');
INSERT 0 1
postgres=# insert into tb_boolean VALUES(12,'n','''n''');
INSERT 0 1
postgres=# insert into tb_boolean VALUES(13,'1','''1''');
INSERT 0 1
postgres=# insert into tb_boolean VALUES(14,'0','''0''');
INSERT 0 1
postgres=# select * from tb_boolean ;
id | col1 | col2
----+------+---------
1 | t | TRUE
1 | f | FALSE
1 | t | tRue
2 | f | fAlse
3 | t | 'tRue'
4 | f | 'fAlse'
7 | t | 't'
8 | f | 'f'
9 | f | 'no'
10 | t | 'yes'
11 | t | 'y'
12 | f | 'n'
13 | t | '1'
14 | f | '0'
(14 rows)
二、布尔类型的操作符
操作符分为逻辑操作符和比较操作符
1.逻辑操作符有:AND、OR、NOT。
SQL标准使用三种值的布尔逻辑:TRUE、FALSE和NULL,NULL代表unknown。
布尔的and、or逻辑运算:
a | b | a AND b | a OR b |
---|---|---|---|
TRUE | TRUE | TRUE | TRUE |
TRUE | FALSE | FALSE | TRUE |
TRUE | NULL | NULL | TRUE |
FALSE | FALSE | FALSE | FALSE |
FALSE | NULL | FALSE | NULL |
NULL | NULL | NULL | NULL |
布尔的not运算:
a | NOT a |
---|---|
TRUE | FALSE |
FALSE | TRUE |
NULL | NULL |
逻辑操作符的两边值可以互换,结果是相同的。
布尔类型使用 IS 作为比较运算符,结果很直观,不多做介绍了。