邏輯結構
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');