如何在PostgreSQL 9.4中找到主表分区的列?

时间:2018-08-22 11:06:33

标签: postgresql partitioning

在PostgreSQL中,我创建了一个主表

CREATE TABLE IF NOT EXISTS table_master(
column_1 text NOT NULL,
column_2 text NOT NULL,
column_3 text NOT NULL
);

和基于列的分区表:column_1,column_2

CREATE TABLE table_col1_col2 (
CONSTRAINT table_col1_col2_pk PRIMARY KEY (column_1, column_2),
CHECK ( column_1 = 'value_1' AND column_2 = 'value_2')
) INHERITS (table_master);

是否有任何选择查询以获取分区的列(column_1,colum_2)?

更新

如果我知道一个子表,我可以使用以下查询:

WITH table_id AS (
SELECT oid 
FROM pg_class
WHERE relname = 'child_table_name'
),
con AS (
SELECT c.conname,
c.contype,
c.conkey,
c.consrc
FROM pg_constraint c INNER JOIN table_id ON c.conrelid = table_id.oid
WHERE c.contype = 'c'
)
SELECT a.attnum,
a.attname
FROM pg_attribute a INNER JOIN table_id ON a.attrelid = table_id.oid
INNER JOIN con s ON a.attnum = ANY(conkey)

最终查询

WITH table_id AS (
SELECT pg_class.oid 
FROM pg_class INNER JOIN pg_inherits ON pg_class.relname::text = pg_inherits.inhrelid::regclass::text
WHERE pg_inherits.inhparent = 'master_table'::regclass
),
con AS (
SELECT c.conname,
c.contype,
c.conkey,
c.consrc
FROM pg_constraint c INNER JOIN table_id ON c.conrelid = table_id.oid
WHERE c.contype = 'c'
)
SELECT a.attnum,
a.attname
FROM pg_attribute a INNER JOIN table_id ON a.attrelid = table_id.oid
INNER JOIN con s ON a.attnum = ANY(conkey)

1 个答案:

答案 0 :(得分:0)

您可以获取主键列。

  

这将返回主数据库所有列的名称和数据类型   tablename表的键:

SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_type
FROM   pg_index i
JOIN   pg_attribute a ON a.attrelid = i.indrelid
                     AND a.attnum = ANY(i.indkey)
WHERE  i.indrelid = 'tablename'::regclass
AND    i.indisprimary;

(source)

这里使用了这样的事实:Postgres通过索引处理主键的唯一性,因此您可以使用pg_index表。