2016-06-01 81 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