postgresql 数据库基本管理

逻辑结构

PostgreSQL教程--逻辑结构:实例、数据库、schema、表之间的关系

数据库基本管理

-- 查询所有数据库
select datname from pg_catalog.pg_database ;

-- 创建数据库
create database jx with encoding 'UTF8' LC_COLLATE= 'C' LC_CTYPE='C' TEMPLATE=template1;

-- 查询数据库编码
SELECT pg_database.datname AS database_name, pg_database.encoding AS database_encoding
FROM pg_database
WHERE pg_database.datname = 'jx'; 

-- 删除数据库
drop database if exists jx;

schema 的基本操作

-- 查询当前数据库下的 schema
SELECT schema_name
FROM information_schema.schemata
WHERE schema_name NOT IN ('information_schema', 'pg_catalog');

建表

参考

PostgreSQL建立自增主键的两种方法

运维笔记--postgresql查看表结构、表名、字段类型、字段注释

建表语句


-- 查询表名
select relname from pg_catalog.pg_stat_all_tables  where schemaname = 'public';

-- 查询表名和表注释
select
	c.relname ,
	b.description
from
	pg_catalog.pg_class c
left join pg_catalog.pg_description b
on
	c.oid = b.objoid
where
	b.objsubid = 0;

-- 查询序列
select * from pg_catalog.pg_sequences ;

-- 删除表
drop table sys_dict_type ;
-- 创建表
create table sys_dict_type(
id bigint primary key,
name varchar(100),
type varchar(100),
group_code  varchar(100),
status char(1)
);

-- 添加表注释
comment on table sys_dict_type is '系统字典类型表';
-- 添加字段注释
comment on column sys_dict_type.name is '字典名称';
comment on column sys_dict_type.type is '字典类型编码';
comment on column sys_dict_type.group_code is '字典分组 (system:系统字典)';
comment on column sys_dict_type.status is '状态 (0:正常 1:停用)';

-- 创建序列
-- owned by 表示关联到特定字段, 删除字段或表的时候自动删除序列
create sequence seq_sys_dict_type increment 1 minvalue 1 maxvalue 9223372036854775807 start with 1 cache 1 owned by sys_dict_type.id;

-- 设置主键默认值为序列的 nextval
alter table sys_dict_type alter column id set default nextval('seq_sys_dict_type');

-- 查询表结构
select
	c.oid ,
	c.relname "table",
	a.attname "column",
	t.typname type,
	a.attlen ,
	a.atttypmod lengthvar,
	a.attnotnull "notnull",
	b.description comment
from
	pg_catalog.pg_class c
left join pg_catalog.pg_attribute a on
	c.oid = a.attrelid
left join pg_catalog.pg_description b on
	a.attnum = b.objsubid,
	pg_type t
where
	c.relname = 'sys_dict_type'
	and a.attnum > 0
	and a.atttypid = t.oid ;

-- 插入数据
insert into sys_dict_type(name,type,group_code,status) values('性别','gender','system','0');
insert into sys_dict_type(name,type,group_code,status) values('模块','module','system','0');
posted @ 2024-06-09 10:21  潼关路边的一只野鬼  阅读(19)  评论(0编辑  收藏  举报