如何在Redshift中查询表的主键

Ale*_*lex 3 postgresql amazon-redshift

我试图使用Postgresql Wiki(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;
Run Code Online (Sandbox Code Playgroud)

不幸的是,它似乎在Redshift中不起作用。我得到这个错误:

ERROR:  op ANY/ALL (array) requires array on right side
Run Code Online (Sandbox Code Playgroud)

我是在做错什么还是这是另一个红移异常?

任何帮助将不胜感激。

小智 5

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)
Run Code Online (Sandbox Code Playgroud)

这不是真的。

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

这是获取表主键的一种方法:

SELECT schemaname,tablename,replace(substr(ddl,POSITION('('in ddl)+1),')','')primary_key FROM admin.v_generate_tbl_ddl WHERE schemaname ='schema'AND tablename ='table'AND upper( ddl)喜欢'%PRIMARY%';

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


小智 5

您可以使用以下sql来获取模式“schemaname”中表“tablename”的主键列表

SELECT
  att.attname
FROM pg_index ind, pg_class cl, pg_attribute att
WHERE 
  cl.oid = 'schemaname."tablename"'::regclass 
  AND ind.indrelid = cl.oid 
  AND att.attrelid = cl.oid
  and att.attnum = ANY(string_to_array(textin(int2vectorout(ind.indkey)), ' '))
  and attnum > 0
  AND ind.indisprimary
order by att.attnum;
Run Code Online (Sandbox Code Playgroud)


Sai*_*olu -1

Redshift 不强制执行主键的概念http://docs.aws.amazon.com/redshift/latest/dg/t_Defining_constraints.html但身份属性可用于设置唯一性。(更多信息请访问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
Run Code Online (Sandbox Code Playgroud)

  • 关于“Redshift 没有主键的概念”,这是不正确的;它们只是不强制执行,但您链接到的页面实际上建议您定义它们。 (3认同)
  • 据我所知,上面的查询实际上并没有对表施加约束。 (2认同)