我想找出一种更好的方法来列出特定模式中的所有唯一约束.我能够用下面这个问题列出它们,这些问题来自于对类似问题的旧答案:

SELECT
    tc.table_schema,
    tc.constraint_name,
    tc.table_name,
    kcu.column_name,
    ccu.table_schema AS foreign_table_schema,
    ccu.table_name AS foreign_table_name,
    ccu.column_name AS foreign_column_name
FROM
    information_schema.table_constraints AS tc
JOIN
    information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
JOIN
    information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
WHERE
    tc.constraint_type = 'UNIQUE' AND tc.table_schema = 'mySchema'

但是这个查询不会返回很好的结果.例如,如果我有这样一张表:

CREATE TABLE myTable (
    id int not null primary key,
    col1 text,
    col2 text,
    col3 text,
    unique (col1, col2, col3)
)

SELECT语句将返回每列的所有9行结果,其他列包含在UNIQUE约束中--包括自身.

Sample output

"public"    "mytable_col1_col2_col3_key"    "mytable"   "col1"  "public"    "mytable"   "col1"
"public"    "mytable_col1_col2_col3_key"    "mytable"   "col1"  "public"    "mytable"   "col2"
"public"    "mytable_col1_col2_col3_key"    "mytable"   "col1"  "public"    "mytable"   "col3"
"public"    "mytable_col1_col2_col3_key"    "mytable"   "col2"  "public"    "mytable"   "col1"
"public"    "mytable_col1_col2_col3_key"    "mytable"   "col2"  "public"    "mytable"   "col2"
"public"    "mytable_col1_col2_col3_key"    "mytable"   "col2"  "public"    "mytable"   "col3"
"public"    "mytable_col1_col2_col3_key"    "mytable"   "col3"  "public"    "mytable"   "col1"
"public"    "mytable_col1_col2_col3_key"    "mytable"   "col3"  "public"    "mytable"   "col2"
"public"    "mytable_col1_col2_col3_key"    "mytable"   "col3"  "public"    "mytable"   "col3"

Expected output

"public"    "mytable_col1_col2_col3_key"    "mytable"   ["col1","col2","col3"]

那么,有没有人可以帮我修复这个查询,以返回唯一约束的美化表示?

推荐答案

您可以直接查询元数据:

SELECT c.conrelid::regclass AS table_name,
       c.conname AS constraint_name,
       array_agg(a.attname ORDER BY k.n) AS columns
FROM pg_constraint AS c
   CROSS JOIN LATERAL unnest(c.conkey) WITH ORDINALITY AS k(c,n)
   JOIN pg_attribute AS a
      ON a.attnum = k.c AND a.attrelid = c.conrelid
WHERE c.contype = 'u'
  AND c.connamespace = 'mySchema'::regnamespace
GROUP BY c.oid, c.conrelid, c.conname;

Postgresql相关问答推荐

如何在gorm中创建一个可读但不可写的字段

Postgres:创建分区需要很长时间

数组格式类型的PostgreSQL日期

在连接字符串并将其附加到 PostgreSQL 中的 where 子句时出现语法错误.怎么修?

在 PostgreSQL 中 Select 数字命名列会返回 ?column?

从网址获取第一个字符串

PostgreSQL:如何避免被零除?

将数组插入 Postgresql 数据库

PostgreSQL - jsonb_each

在 PostgreSQL docker 镜像中创建表

断言错误:Django-rest-Framework

当记录包含 json 或字符串的混合时,如何防止 Postgres 中的invalid input syntax for type json

错误:must be owner of language plpgsql

使用 pg-promise 插入多条记录

为 postgresql 存储过程设置隔离级别

将 Windows 上的 .sql 文件导入到 postgresql

为什么 rake db:migrate 有时会在 structure.sql 中添加尾随空格?

PostgreSQL:如果不存在则创建表 AS

PostgreSQL 多种认证方式

在 Select (PostgreSQL/pgAdmin) 中将布尔值返回为 TRUE 或 FALSE