postgreSQL数据库常用语法

postgreSQL常用语法

1、CRUD增删改查

创建用户角色
create  user ldc  with password 'ldc-';
创建数据库
create DATABASE school_info 
ENCODING  ='utf-8'  --指定字符集    
TABLESPACE = pg_default 
owner ldc; --设置数据库所有者
grant all privileges on database school_info  to ldc;  --将 school_info 数据库的所有权限赋予 ldc
创建表
-- 创建班级表
create table class_info
(
    id                    serial not null
                          constraint class_info_pk
                          primary key,
    name                  varchar,
    write_date            timestamp
);

comment on table class_info is '班级表';
comment on column class_info.name is '班级名称';
comment on column class_info.write_date is '修改时间';
alter table class_info  owner to ldc;   -- 修改表拥有者为ldc


--创建表
-- 创建学生表,id自增
-- id      serial not null  表示id自增
-- id      integer not null  表示id不自增
create table student
(
    id                    serial not null
                          constraint student_pk
                          primary key,
    name                  varchar,
    class_id             integer  references "class_info"("id"),
    height                numeric,
    weight                numeric,
    write_date            timestamp
);

comment on table student is '学生表';
comment on column student.name is '名称';
comment on column student.class_id is '班级ID';
comment on column student.height is '身高';
comment on column student.weight is '体重';
comment on column student.write_date is '修改时间';
alter table student  owner to ldc;   -- 修改表拥有者为ldc
增加记录
insert into "class_info" (name,write_date) values('高一八班', '2010-09-09 11:33:00');

insert into "student" (name,class_id, height, weight, write_date) 
	values ('小梁',1,160,50, '2010-09-09 12:33:00'),
	('小刘',1,155,50, '2010-10-08 13:33:00'),
	('小强',1,175,60, '2010-11-12 13:33:00');
删除表
-- 如果表存在就先删除
drop table if exists student;
删除记录
delete from student where name='小梁'
删除字段
alter table 表名 drop column 列名 ;
比如
alter table student drop column sex ;
更新记录
update student set name='大梁' where id=3
新增或更新
--如果id冲突就更新
insert into student(id, name,class_id) 
	values(1,'小兰',1)
	on conflict(id) 
	do update set name ='小芳';

--如果id冲突就什么也不做
insert into  student(id, name,class_id)
   values(3,'小明',1)
   on conflict(id) do nothing;
联合子集更新

# 联合子集更新,把sale_order_line的name连接换行符,然后按id更新到表a_test中对应的name
update a_test set name=array_to_string(array(select name from sale_order_line where order_id=a_test.id),'<br/>');
把一个表中的数据插入到另一个表中
--把一个表中的数据插入到另一个表中
insert into 目标表名 (column1,column2,columnn) select value1,value2,valuen from  源表名
比如:
insert into student (name, classs_name,create_date) select  student_name as name, class_name, now() from class_table;
增加字段
alter table student add column sex bool;
查看用户角色
select * from pg_roles; 
查看当前时间
now()
select now()
查看表所有字段
select * from information_schema.columns where table_schema='public' and table_name='student';
查看数据库所有表名
select tablename from pg_tables where schemaname='public'

2、按条件查询

升降序
-- 对查询结果按id降序显示
select * from student order by id desc

-- 对查询结果按id升序显示
select * from student order by id asc
转义字符
-- 转义字符, 查找name中包含单引号的记录
select * from student where name like  E'%\'%'
查看表记录总数

方式一:

select relname as TABLE_NAME, reltuples as rowCounts from pg_class where relkind = 'r' and relnamespace = (select oid from pg_namespace where nspname='public') order by rowCounts desc;

方式二:

select count(*) from student;

3、常用函数

array:将结果转换为数组
SELECT array(SELECT "name" FROM student);

结果:{小芳,小刘,大梁}

array_to_string:将数组合并为字符串
select array_to_string(array[1,2,3], ',');

结果:1,2,3

cast:类型转换
select cast(id as varchar) from student;  --把id 从integer转成varchar
concat:字符串拼接
select 
concat('学生:id=', cast(s.id as varchar), '姓名:',s.name, '班级:',ci.name) 
from student as s
left join class_info as ci on ci.id=s.class_id

结果:学生:id=1姓名:小芳班级:高一八班

concat_ws:多字符串拼接(不用转换类型)
select 
concat_ws('学生:id=', s.id, '姓名:',s.name, '班级:',ci.name) 
from student as s
left join class_info as ci on ci.id=s.class_id
substring:字符截取
select substring('abcd',1,2); -- 表示下标从1开始,截取2个字符

结果:ab

row_number():定义行编号
--对行记录定义行编号,使用函数ROW_NUMBER()
select           
		ROW_NUMBER() OVER (ORDER BY id desc) AS sequence_number,
		id,name
from
		student
array_agg:把表达式变成一个数组
-- 名称降序然后组合成数组
select array_agg(name order by name asc) from student

结果:{大梁,小芳,小刘}

unnest:一行变多行
select unnest(array_agg(name order by name asc)) from student

结果:{大梁,小芳,小刘} ->

大梁

小芳

小刘

array:把结果变成数组类型
select ARRAY(select unnest(array_agg(name order by name asc))) from student

结果:{大梁,小芳,小刘}

合并查询同一列的多条记录
# PostgreSQL合并查询同一列的多条记录,针对一对多,多对多字段
比如表:

id   name                  
1    小明                   
1    小红                     id   name
1    小亮        -->          1    小明,小亮,小红
2    小强                     2    小强,小王
2    小王

SELECT 
    id, array_to_string(ARRAY(SELECT unnest(array_agg(name order by name desc))),',') AS all_name
FROM  
    student
GROUP BY id;
to_char:类型转换
select to_char(write_date, 'yyyy-MM-dd hh24:MI:ss') from student
case:枚举
--case语句
select
case 
	when score > 80 and score < 90 then '良'
	when score > 90 then '优秀'
else '中'
end as result
from student;
with :临时表
--临时表、字符串合并、类型转换、时间格式转换、当前时间
WITH TEMP AS ( 
	SELECT CAST (concat (write_date, '-01' ) AS TIMESTAMP ) 
	   AS account_period_time 
		 FROM student AS s ) 
SELECT
	account_period_time,
	to_char(CURRENT_DATE,'yyyy-MM-dd hh24:MI:ss') as current_date,
	to_char( account_period_time, 'yyyy' ) as year,
	to_char( account_period_time, 'MM' ) as month,
	to_char( account_period_time, 'dd' ) as day 
FROM TEMP

结果:

account_period_time	current_date	    year	month	day
2019-06-01 0:00:00	2020-06-24 00:00:00	2019	 06	     01
2019-06-01 0:00:00	2020-06-24 00:00:00	2019	 06	     01
多个临时表


# 多个临时表
WITH temp_student AS ( SELECT ID, NAME, sex FROM student WHERE sex = TRUE ),
temp_class AS (
	SELECT
		ID,
		NAME,
		student_id,
		teacher_id
	FROM
		the_class 
	),
	temp_teacher AS (
	SELECT 
	  ID,
		NAME,
		age 
	FROM
		teacher 
	) 
	SELECT
	ts.NAME AS student_name,
	tc.NAME AS class_name,
	te.NAME AS teacher_name
	from temp_student as ts
	LEFT JOIN temp_class AS tc ON tc.student_id = ts.ID  
	LEFT JOIN teacher AS te ON te.id = tc.teacher_id  
coalesce:返回参数中的第一个非null的值
-- null转成有意义的值
select coalesce(name, '') as name from student;  --name为null,就转为空字符串

4、其它

# 保留重复记录中的最小id的SQL语句
select min(id) as id,co1,co2 from test group by co1,co2

# 使用 interval 时间相加减(+/-)
当前时间 + 10秒,
select to_char(now() + interval '10 second', 'yyyy-mm-dd hh24:mi:ss')  as reqDate from account_period;
当前时间 - 10select to_char(now() + interval '-10 second', 'yyyy-mm-dd hh24:mi:ss')  as reqDate from account_period;
 
当前时间 + 10分,
select to_char(now() + interval '10 minute', 'yyyy-mm-dd hh24:mi:ss')  as reqDate  from account_period;
 
当前时间 + 10时,
select to_char(now() + interval '10 hour', 'yyyy-mm-dd hh24:mi:ss')  as reqDate from account_period;
 
当前时间 + 10天,
select to_char(now() + interval '10 day', 'yyyy-mm-dd hh24:mi:ss')  as reqDate from account_period;

当前时间 + 10年,
select to_char(now() + interval '10 year', 'yyyy-mm-dd hh24:mi:ss')  as reqDate from account_period;


# 判断字段是否全为数字
select '1234' ~ '^([0-9]+[.]?[0-9]*|[.][0-9]+)$'
select '1234a' ~ '^([0-9]+[.]?[0-9]*|[.][0-9]+)$'
select * from student where score  ~ '^([0-9]+[.]?[0-9]*|[.][0-9]+)$'

后记

【后记】为了让大家能够轻松学编程,我创建了一个公众号【轻松学编程】,里面有让你快速学会编程的文章,当然也有一些干货提高你的编程水平,也有一些编程项目适合做一些课程设计等课题。

也可加我微信【1257309054】,拉你进群,大家一起交流学习。
如果文章对您有帮助,请我喝杯咖啡吧!

公众号

公众号

关注我,我们一起成长~~

  • 6
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Linux服务器常用命令(简化版) 11 1 1 Linux服务器常用命令(简化版)全文共74页,当前为第1页。Linux服务器常用命令(简化版)全文共74页,当前为第1页。Linux服务器常用命令(简化版) Linux服务器常用命令(简化版)全文共74页,当前为第1页。 Linux服务器常用命令(简化版)全文共74页,当前为第1页。 文件管理类命令 1.keytool命令 进行密钥和证书管理的工具,证书也叫CA证书,比较标准全称为"公开密钥认证";密钥就是用来加解密用的文件或者字符串。 语法格式:keytool [命令] 常用参数: 序号 参数 说明 备注 1 -certreq 生成证书请求 2 -changealias 更改条目的别名 3 -delete 删除条目 4 -exportcert 导出证书 5 -genkeypait 生成密钥对 6 -genseckey 生成密钥 7 -gencert 根据证书请求生成证书 8 -importcert 导入证书或证书链 9 -importkeystore 从其他密钥库导入一个或所有条目 10 -keypasswd 更改条目的密钥口令 11 -list 列出密钥库中的条目 12 -printcert 打印证书内容 Linux服务器常用命令(简化版)全文共74页,当前为第2页。Linux服务器常用命令(简化版)全文共74页,当前为第2页。13 Linux服务器常用命令(简化版)全文共74页,当前为第2页。 Linux服务器常用命令(简化版)全文共74页,当前为第2页。 -printcertreq 打印证书请求的内容 14 -printcrl 打印CRL文件的内容 15 -storepasswd 更改密钥库的存储口令 2.rndc-confgen命令 为rndc生成配置文件,rndc命令通过TCP连接与DNS服务器通信,发送使用数字签名认证的命令。 语法格式:rndc-confgen [参数] 常用参数: 序号 参数 说明 备注 1 -t<目录> 指定一个运行chroot目录,rndc.key文件的副本将被写入到该目录中 2 -s<IP地址> 为来自rndc的命令通道连接指定监听的IP地址。默认值是环回地址127.0.0.1 3 -c<密钥文件> 指定备用位置的rndc.key密钥文件 4 -b<密钥大小> 指定密钥的大小,单位是位。必须介于1和512位之间,默认值是128 5 -p<端口> 为来自rndc的连接指定监听的命令通道端口。默认值是953 6 -u<用户> 设置生成的rndc.key密钥文件的所有者 7 -r<随机文件> 指定用于生成授权随机数据源 8 -k<密钥名称> 指定rndc认证密钥的密钥名称 9 -a 自动rndc配置,创建密钥文件/etc/rndc.key Linux服务器常用命令(简化版)全文共74页,当前为第3页。Linux服务器常用命令(简化版)全文共74页,当前为第3页。3.umount.nfs命令 Linux服务器常用命令(简化版)全文共74页,当前为第3页。 Linux服务器常用命令(简化版)全文共74页,当前为第3页。 作用是卸载NFS文件系统,NFS全称为Network File System。 语法格式:umount.nfs [本地目录] [参数] 常用参数: 序号 参数 说明 备注 1 -f 在无法访问NFS系统的情况下强制卸载文件系统 2 -n 不更新/etc/mtab文件 3 -v 显示详细信息 4 -r 在卸载失败的情况下,尝试只读挂载 4.createdb命令 作用是可以创建一个PostgreSQL数据库PostgreSQL是一个功能非常强大的、源代码开放的客户/服务器关系型数据库管理系统(RDBMS)。 语法格式:createdb [参数] [数据库] [描述] 常用参数: 序号 参数 说明 备注 1 -D<表空间> 数据库默认表空间 2 -e 显示发送到服务端的命令 3 -O<所有者> 新数据库的所属用户 4 -E<编码> 指定数据库编码 5 -h<主机名> 数据库服务器的主机名 Linux服务器常用命令(简化版)全文共74页,当前为第4页。Linux服务器常用命令(简化版)全文共74页,当前为第4页。6 Linux服务器常用命令(简化版)全文共74页,当前为第4页。 Linux服务器常用命令(简化版)全文共74页,当前为第4页。 -p<端口> 数据库服务器端口号 7 -U<用户> 连接的用户名 8 -w 永远不提示输入口令 9 -W 强制提示输入口令 10 -T<模版数据库> 指定要复制的数据库模版 5.vacuumdb命令 优化一个PostgreSQL数据库。vacuumdb命令也将产生由PostgreSQL查询优化器所
MySQL和PostgreSQL是两种常用的关系型数据库管理系统(RDBMS)。它们使用的是不同的SQL语法和功能。因此,将MySQL的SQL语句转换为PostgreSQL语法是一项常见的任务。 为了实现这种转换,可以使用一些工具和技术。以下是一些常用的工具和方法: 1. 使用在线转换工具:有一些在线工具可用于将MySQL语句转换为PostgreSQL语法。你只需将MySQL语句粘贴到工具中,然后选择将其转换为PostgreSQL语法。这些工具会自动将语句转换为相应的PostgreSQL语法。一些流行的在线转换工具包括SQLines SQL转换器和fromsqltocode工具。 2. 使用第三方软件:有一些第三方软件可用于将MySQL数据库迁移到PostgreSQL,并自动转换语句。例如,SQLMaestro的MySQL到PostgreSQL工具可以帮助你轻松将MySQL语句转换为PostgreSQL语法,并将数据库迁移到PostgreSQL。 3. 手工转换:如果对SQL语法和MySQL和PostgreSQL的功能有深入的了解,也可以手动将MySQL语句转换为PostgreSQL语法。这需要查看和理解两个数据库语法规则,然后逐个转换每个语句。手动转换可能需要花费一些时间和精力,但对于复杂的查询可能是最灵活和可靠的方法。 转换MySQL语法PostgreSQL语法需要注意以下几个主要差异: - 数据类型:MySQL和PostgreSQL使用不同的数据类型,因此在转换过程中需要注意这一点,并将MySQL的数据类型转换为PostgreSQL的等效类型。 - 语法:MySQL和PostgreSQL在某些语法方面也有所不同,例如连接语法、子查询语法等。所以需要了解并适当地转换这些差异。 总之,将MySQL语法转换为PostgreSQL语法的工具和方法有很多选择。无论选择哪种方法,都需要对SQL语法和MySQL、PostgreSQL的特定功能有深入的了解。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东木月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值