2016-06-01 44 views
0

来查询表的主键我试图用代码建议对PostgreSQL的维基(https://wiki.postgresql.org/wiki/Retrieve_primary_key_columns):如何在红移

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; 

不幸的是,它似乎并没有在红移工作。我得到这个错误:

ERROR: op ANY/ALL (array) requires array on right side 

我做错了什么或这是又一个红移异常?

任何帮助将不胜感激。

+0

你用什么Postgres的版本?另外:你试图获得索引的是哪张表? – perzsa

回答

1

红移没有主键http://docs.aws.amazon.com/redshift/latest/dg/t_Defining_constraints.html但身份attritube的概念可以用来设定唯一性。 (在http://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html更多信息)

对于现有的表的详细信息,可以使用下面的查询

select column_name, is_nullable, data_type, character_maximum_length 
from information_schema.columns 
where table_schema='schema_name' 
and table_name='table_name' 
order by ordinal_position 
+1

re“Redshift没有主键的概念”,这是不正确的;他们只是没有执行,但你链接到的页面实际上建议你定义它们。 – chorbs

0

试着用这一个的帮助: https://bitbucket.org/zzzeek/sqlalchemy/pull-request/6/sqlalchemy-to-support-postgresql-80/diff

SELECT attname column_name, attnotnull, 
    format_type(atttypid, atttypmod) as column_type, atttypmod, 
    i.indisprimary as primary_key, 
    col_description(attrelid, attnum) as description 
FROM pg_attribute c 
    LEFT OUTER JOIN pg_index i 
    ON c.attrelid = i.indrelid AND i.indisprimary AND 
    c.attnum = ANY(string_to_array(textin(int2vectorout(i.indkey)), ' ')) 
where c.attnum > 0 AND NOT c.attisdropped AND c.attrelid = :tableOid 
order by attnum 
1
Redshift doesn't have the concept of primary keys http://docs.aws.amazon.com/redshift/latest/dg/t_Defining_constraints.html but identity attritube can be used to set uniqueness. (more info at http://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html) 

这是不正确的。

Redshift不强制执行主键约束,但它们可以使用。在自动化数据管道或数据质量检查时,它们非常有用。在设计星型模式时,它们也被红移推荐,因为它们被查询优化器用作提示。 https://aws.amazon.com/blogs/big-data/optimizing-for-star-schemas-and-interleaved-sorting-on-amazon-redshift/

这里有一个方法来得到一个表的主键:

SELECT SCHEMANAME,表名,更换(SUBSTR(DDL,POSITION( '(' IN DDL)+1), ')', '')primary_key FROM admin.v_generate_tbl_ddl WHERE schemaname ='schema'AND tablename ='table'AND upper(ddl)LIKE'%PRIMARY%';

的视图“admin.v_generate_tbl_ddl”的代码是在这里:https://github.com/awslabs/amazon-redshift-utils/tree/master/src/AdminViews