在PostgreSQL表中使用模式名称作为外键

时间:2014-02-12 15:51:20

标签: sql postgresql postgresql-8.4

是否可以使用模式名称作为PostgreSQL中表的外键?类似的东西:

create table account(
    id varchar(30) references information_schema.schemata(schema_name)
);

运行上面的SQL,我收到以下错误:

SQL Error:

ERROR:  referenced relation "schemata" is not a table

In block:

create table account(
    id varchar(30) references information_schema.schemata(schema_name)
);

我们的想法是在创建帐户之前检查帐户的架构是否存在。

1 个答案:

答案 0 :(得分:3)

您只能创建对具体表格的FK引用 - 而不是information_schema.schemata

等视图
regress=> \dv information_schema.schemata
                List of relations
       Schema       |   Name   | Type |  Owner   
--------------------+----------+------+----------
 information_schema | schemata | view | postgres
(1 row)

支持视图的基础pg_catalog.pg_namespace表:

regress=> select pg_get_viewdef('information_schema.schemata');
                                           pg_get_viewdef                                            
-----------------------------------------------------------------------------------------------------
  SELECT (current_database())::information_schema.sql_identifier AS catalog_name,                   +
     (n.nspname)::information_schema.sql_identifier AS schema_name,                                 +
     (u.rolname)::information_schema.sql_identifier AS schema_owner,                                +
     (NULL::character varying)::information_schema.sql_identifier AS default_character_set_catalog, +
     (NULL::character varying)::information_schema.sql_identifier AS default_character_set_schema,  +
     (NULL::character varying)::information_schema.sql_identifier AS default_character_set_name,    +
     (NULL::character varying)::information_schema.character_data AS sql_path                       +
    FROM pg_namespace n,                                                                            +
     pg_authid u                                                                                    +
   WHERE ((n.nspowner = u.oid) AND pg_has_role(n.nspowner, 'USAGE'::text));
(1 row)

regress=> \dt pg_catalog.pg_namespace
              List of relations
   Schema   |     Name     | Type  |  Owner   
------------+--------------+-------+----------
 pg_catalog | pg_namespace | table | postgres
(1 row)

...也不是外键的合法目标,因为PostgreSQL不支持对系统表的外键引用:

regress=> CREATE TABLE blah (x text references pg_catalog.pg_namespace(nspname));
ERROR:  permission denied: "pg_namespace" is a system catalog

所以......你不能。