https://www.postgresql.org/docs/9.4/ddl-schemas.htmlhtml
A database contains one or more named schemas, which in turn contain tables. Schemas also contain other kinds of named objects, including data types, functions, and operators. The same object name can be used in different schemas without conflict; for example, both schema1 and myschema can contain tables named mytable. Unlike databases, schemas are not rigidly separated: a user can access objects in any of the schemas in the database he is connected to, if he has privileges to do so.
在建立一个新的 database 时, PostgreSQL 会自动为其建立一个 名为 public 的 schema。 若是未设置 search_path 变量,那 么 PostgreSQL 会将你建立的全部对象默认放入 public schema 中。_
使用schema带来的好处sql
code example:数据库
CREATE SCHEMA myschema;
访问schema的表post
schema.table
实际上,更通用的语法postgresql
database.schema.table
在schema里建立表code
CREATE TABLE myschema.mytable ( ... );
删除空schemahtm
DROP SCHEMA myschema;
删除schema 而且也删除其中的对象对象
DROP SCHEMA myschema CASCADE;
为某个用户建立schemaget
CREATE SCHEMA schemaname AUTHORIZATION username;
默认建立的表都在public schema
里it
下面两条语句是等价的
CREATE TABLE products ( ... ); CREATE TABLE public.products ( ... );
当执行类 似 SELECT * FROM dogs
这种语句时, PostgreSQL 是怎么知道要查的是哪一个 schema 中的表 呢?
能够加schema前缀解决, 也能够设置 search_path
变量解决
查看
SHOW search_path;
search_path -------------- "$user",public
PostgreSQL 有一个少为人知的系统变量叫做 user , 它表明了当前登陆用户的名称。 执行 SELECT user 就能看到其名称。
对于search_path 里的$user, 若是当前登陆的角色是doggy
, 那么全部的查询都会优先去doggy
schema 中寻找目标表, 若是找不到才会去 public schema 下找
设置新的schema倒search path里
SET search_path TO myschema,public;
这样 默认 建立访问 table 都在 myschema
schema里