1.获取当前时间函数,年月日时分秒
select now();
2022-01-12 22:18:32.045755+08
2.将当前时间转化为字符串 年月日 或者是灵活取值
select to_char(now(),'yyyy-MM-DD')
2022-01-12
3.获取前一个月(现在是2022年1月)
select to_char(now() - interval '1 month','yyyy-MM');
2021-12
4.获取前一天(现在是2022年1月12日)
select to_char(now() - interval '1 day','yyyy-MM-DD');
2022-01-11
5.灵活使用 like 直接用SQL 不需要用mybatis 使用 ||
where
signstatus = '1'
and nowtime like '%'||to_char(now() - interval '1 month','yyyy-MM')||'%'
6.获取指定月份的天数
select date_part('days', date_trunc('month', to_timestamp('2021-12', 'yyyy-MM-dd hh24:mi:ss')) + '1 month'::interval - '1 day':: interval)
7.给定开始时间、结束时间获取之间的天数
select to_char(t,'MM') as day1
from
generate_series('2021-12-28'::DATE,'2022-01-03', '1 day') as t
拓展
select count(r.day1) from
(select to_char(t,'MM') as day1
from
generate_series('2021-12-28'::DATE,'2022-01-03', '1 day') as t)r where r.day1 = '12';
8.创建自增序列
从1开始
CREATE SEQUENCE 序列名 START 1;
示例
CREATE SEQUENCE kx_sign_statistics2_id START 1;
从指定数字开始
CREATE SEQUENCE 序列名 START WITH 1490527538458529792;
示例
CREATE SEQUENCE kx_sign_statistics2_id START WITH 1490527538458529792;
9.将序列与指定的表字段绑定
ALTER TABLE tablename ALTER COLUMN 字段名 SET DEFAULT nextval('序列名'::regclass);
示例
ALTER TABLE kx_sign_statistics2 ALTER COLUMN id SET DEFAULT nextval('kx_sign_statistics2_id'::regclass);
10.UUID
- 在pgsql中安装扩展
create extension "uuid-ossp" ;
- 查询
select uuid_generate_v4()
- 注意:必须是超级用户才能安装这个扩展
11.权限不够的情况下进行表的复制
select * into table1 from table2;
将表2的结构以及数据复制到表1中,要求表1 不存在