postgresql 常用函数

165 阅读1分钟

######1. age 函数

select age('2019-11-28',now()) < interval '2 hour' 减去当前时间,是否小于2小时

返回类型 描述 例子 结果 age(timestamp,timestamp) interval 减去参数,生成一个使用年、月的"符号化"的结果 age('2001-04-10', timestamp '1957-06-13') 43 years 9 mons 27 days

函数 返回类型 描述 例子 结果
age(timestamp,timestamp) interval 减去参数,生成一个使用年、月的"符号化"的结果 age('2001-04-10', timestamp '1957-06-13') 43 years 9 mons 27 days
2. case 函数
CREATE TABLE test (

  sex  varchar(255) 
)
;
insert into test (sex)values('1');
insert into test (sex)values('2');
insert into test (sex)values('1');

--case简单函数

select 
		 case sex
  when '1' then '男'
  when '2' then '女' 
	   end bieming
  
	from test

--case搜索函数

select 
		case 
		 when sex = '1' then '男'
     when sex = '2' then '女'
     else '其他' end bieming
		 from test

end 后面是别名

  1. 处理空值
COALESCE()
select  COALESCE(null,12)

image.png

  1. 多字段模糊查询
select concat_ws(',','11','22','33');

SELECT * from tab1 t where t.col1 like '%a%';

SELECT * from tab1 t where t.col1 like '%' || 'a' || '%';

SELECT * from tab1 t where t.col1 like  concat(concat('%','a'),'%');

如上三种写法的等效的,最常用的是第一张写法,第二种第三种使用拼接,但是不同在于 || 可以无限拼接,类似于拼接字符串时候的 +,而concat 是oracle中的函数,CONCAT(char1 , char2),此函数中有且仅有2个参数,所以第三种写法拼接了2次。 参考: