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裏