函数和操作符

psql命令:\df,\do查看可以用的function和operators。

1.逻辑操作符

  逻辑操作符:AND、OR、NOT  布尔值:TRUE、FLASE、NULL。NULL代表未知

1、注意表达式的计算顺序,如
select not true and false; -- false
== select (not true) and false; -- false
!= select not (true and false); -- true

select not false or false and false; -- true
== select (not false) or (false and false);

2、注意与NULL计算的结果
select true and null; -- null
select false and null; --false
select null and null; -- null
select true or null; --ture
select false or null; -- null
select null or null; -- null
select not null; -- null

2.比较操作符

2.1 <>和!=是完全等价的,在分析阶段,!=被转换成<>

2.2 between...and 

     a between x and y 等效于 a>=x and a<=y;a NOT BETWEEN x AND y等价于 a < x OR a > y,※注意:通常x <= y。若x>y,则a>=x and a<=y是空集,永远返回false。

     如果使用between symmetric(对称的),"and“左边的值不要求小于右边,若左边大于右边,会自动交换。 

postgres=# select 3 between symmetric 4 and 1;--true
postgres=# select 3 between 4 and 1;--false

 2.3 expression IS NULL

     判断值是否为空,expression IS NULL或者expression ISNULL,不要写成expression = null,因为null是表示未知值,两个未知值是无法判断是否相等的。如果一定要这么用的话,可以配置postgresql.conf中的transform_null_equals,如果是enabled,则x=NULL 转换成x IS NULL.

     如果expression是row-valued,ISNULL 只有当所有的值为空,ISNOTNULL只有当所有值不为空的时候才返回true,其余情况均返回false,因此这两个的取值并不是都相反。

如:

test=# SELECT ROW(1,NULL) IS NULL;//false
test=# SELECT ROW(1,NULL) IS NOT NULL;//false

     当有一个输入为NULL,那么普通的比较操作符生成NULL(unknown),既不是True也不是false。例如

postgres=# select 7 = null;
?column?
----------

(1 行)

postgres=# select 7=7;
?column?
----------
t
(1 行)

2.4 IS(NOT) DISTINCT FROM

当没有NULL输入时候,等同于<>,当有NULL输入时,如下:

expression IS DISTINCT FROM expression :都为null返回false,有一个null返回true。

expression IS NOT DISTINCT FROM expression:都为null返回true,有一个null返回false

postgres=# select null is distinct from null;--false
postgres=# select 7 is distinct from null;--true

这样NULL就被当成了普通数据对待,而不是"UNKNOWN"

2.4一些boolean值的操作

expression IS TRUE
expression IS NOT TRUE
expression IS FALSE
expression IS NOT FALSE
expression IS UNKNOWN
expression IS NOT UNKNOWN

以上这些输入必须是Boolean类型的值。

 3.数学操作符

^ :求幂   

|/ :平方根  ||/:立方根

 !:j阶乘    !!:阶乘(!!5)

@:绝对值(@-5 = 5)

~:按位取反(~1=-2)

    PS:按位取反的意思就是每一位取反,0变1,1变0。一旦看到出现负数,那么这个数一定是按有符号数的规则来表示的。一个二进制数按位取反并加一以后就可以得到它自己的负数的补码,也就是说: ~x+1=-x。1:00000001,~1:11111110,-2:~(00000010)+1=11111110.计算机中有源码,补码,反码。

#:xor(异或:不同为1,相同为0,在别的运算中用^表示)

位操作符只能用于整型数据类型和位串类型,其他的操作符可以用于所有的数值类型。

4.字符串操作

字符串连接操作||:至少有一个字符串类型,否则需要显式的转换到text

substring(string from int for int):for后面的int表示截取的字符数。

5.LIKE

string [not]like pattern

如果pattern中不包含%或者_,则相当于=。_匹配单个字符,%匹配0个或多个字符。

ILIKE可以替换like而忽略大小写。

~~等同于like,~~*等同于ILIKE。

 

 

posted @ 2012-12-28 16:39  lanse_yan  阅读(315)  评论(0编辑  收藏  举报