TeleDB有一个运行变量叫search_path,其值为模式名列表,用于配置访问数据对象的顺序,如下所示。
当前连接用户。
teledb=# select current_user;
current_user
--------------
teledb
(1 row)
显示当前search_path,搜索路径只配置为$user, public,其中 $user为当前用户名,即上面的current_user 值teledb。
teledb=# show search_path;
search_path
-----------------
"$user", public
(1 row)
不指定模式创建数据表,则该表存放于第一个搜索模式下面。第一个模式找不到的情况下选择第二个,依次顺序查找。
teledb=# create table t2(id int, content text);
CREATE TABLE
teledb=# \dt t2
List of relations
Schema | Name | Type | Owner
--------+------+-------+---------
public | t2 | table | teledb
(1 row)
--由于没有teledb模式,所以表默认放到了public模式下
-- 创建teledb模式后再次建表,表建到了teledb模式下
teledb=# create schema teledb;
CREATE SCHEMA
teledb=# create table t3(id int, content text);
CREATE TABLE
teledb=# \dt t3
List of relations
Schema | Name | Type | Owner
---------+------+-------+---------
teledb | t3 | table | teledb
(1 row)
指定表位于某个模式下,不同模式下表名可以相同。在public模式下创建t3表
teledb=# create table public.t3(id int, content text);
CREATE TABLE
teledb=# \dt public.t3
List of relations
Schema | Name | Type | Owner
--------+------+-------+---------
public | t3 | table | teledb
(1 row)
同名的表查询时,没有指定shema时,始终只会查到前面模式的表数据。
-- 插入数据到public.t3表
teledb=# insert into public.t3 values(1,'test');
INSERT 0 1
-- 由于teledb模式在第一顺位,且存在同名表,所以始终是teledb模式下的空表
teledb=# select * from t3;
id | content
----+---------
(0 rows)
-- 指定public模式去查询可以查到插入的数据
teledb=# select * from public.t3;
id | content
----+---------
1 | test
(1 row)
访问不在搜索路径的对象时,需要写全路径。
teledb=# create table test1.t4 (id int, name char);
CREATE TABLE
teledb=# select * from t4;
ERROR: relation "t4" does not exist
LINE 1: select * from t4;
^
teledb=# select * from test1.t4;
id | name
----+------
(0 rows)
上面出错是因为模式test1没有配置在search_path搜索路径中。