PostgreSQL:架构的使用方法
前提
假设用户是scott,可以登录数据库city。
$ psql -U scott city
psql (15.2)
"help"でヘルプを表示します。
city=>
创建用户和数据库的方法
su postgres
psql < create.sql
create user scott with password 'tiger123';
create database city;
alter database city owner to scott;
在本地连接时,设定为无需密码。
(省略)
local all all trust
(省略)
创建架构和表
在数据库中创建以下三个模式(schemas):city。
茨城县
栃木县
群马县
针对每个城市,创建一个名为”cities”的数据表。
create schema ibaraki;
create table ibaraki.cities (id varchar(10) primary key, name text, population int, date_mod date);
insert into ibaraki.cities values ('t0821','水戸',72814,'2011-6-14');
insert into ibaraki.cities values ('t0822','土浦',72814,'2011-7-21');
-----
create schema tochigi;
create table tochigi.cities (id varchar(10) primary key, name text, population int, date_mod date);
insert into tochigi.cities values ('t0931','宇都宮',72814,'2012-4-10');
insert into tochigi.cities values ('t0932','小山',72814,'2012-8-24');
-----
create schema gunma;
create table gunma.cities (id varchar(10) primary key, name text, population int, date_mod date);
insert into gunma.cities values ('t1041','前橋',72814,'2013-9-18');
insert into gunma.cities values ('t1042','高崎',72814,'2013-7-21');
执行
psql -U scott city < create.sql
确认结果
$ psql -U scott city
psql (15.2)
"help"でヘルプを表示します。
city=> select * from ibaraki.cities;
id | name | population | date_mod
-------+------+------------+------------
t0821 | 水戸 | 72814 | 2011-06-14
t0822 | 土浦 | 72814 | 2011-07-21
(2 行)
city=> select * from tochigi.cities;
id | name | population | date_mod
-------+--------+------------+------------
t0931 | 宇都宮 | 72814 | 2012-04-10
t0932 | 小山 | 72814 | 2012-08-24
(2 行)
city=> select * from gunma.cities;
id | name | population | date_mod
-------+------+------------+------------
t1041 | 前橋 | 72814 | 2013-09-18
t1042 | 高崎 | 72814 | 2013-07-21
(2 行)
city=>
展示模式
city=> \dn
スキーマ一覧
名前 | 所有者
---------+-------------------
gunma | scott
ibaraki | scott
public | pg_database_owner
tochigi | scott
(4 行)
显示桌子
city-> \dt *.cities
リレーション一覧
スキーマ | 名前 | タイプ | 所有者
----------+--------+----------+--------
gunma | cities | テーブル | scott
ibaraki | cities | テーブル | scott
public | cities | テーブル | scott
tochigi | cities | テーブル | scott
(4 行)
按照模式分类显示表格
city-> \dt ibaraki.*
リレーション一覧
スキーマ | 名前 | タイプ | 所有者
----------+--------+----------+--------
ibaraki | cities | テーブル | scott
(1 行)
city-> \dt gunma.*
リレーション一覧
スキーマ | 名前 | タイプ | 所有者
----------+--------+----------+--------
gunma | cities | テーブル | scott
(1 行)
city-> \dt ibaraki.*
リレーション一覧
スキーマ | 名前 | タイプ | 所有者
----------+--------+----------+--------
ibaraki | cities | テーブル | scott
(1 行)
删除模式
drop schema ibaraki cascade;
drop schema tochigi cascade;
drop schema gunma cascade;
执行
psql -U scott city < drop.sql
当前模式的显示
select current_schema();
修改架构
set search_path = tochigi