【问题标题】:How to extract the names of unique columns of a table in PostgreSQL?如何在 PostgreSQL 中提取表的唯一列的名称?
【发布时间】:2020-04-04 14:49:33
【问题描述】:
假设我在 PortreSQL 中有一个表定义为:
CREATE TABLE my_table (
id serial not null primary key,
var1 text null,
var2 text null unique,
var3 text null,
var4 text null unique
);
是否有对information_schema 的查询仅提供唯一列的名称?理想的反应应该是:
var2
var4
查询应该同时忽略多个列的唯一键。
【问题讨论】:
标签:
postgresql
information-schema
【解决方案1】:
你需要information_schema.table_constraints和information_schema.constraint_column_usage:
SELECT table_schema, table_name, column_name
FROM information_schema.table_constraints AS c
JOIN information_schema.constraint_column_usage AS cc
USING (table_schema, table_name, constraint_name)
WHERE c.constraint_type = 'UNIQUE';
如果你想跳过多于一列的约束,请使用分组:
SELECT table_schema, table_name, min(column_name)
FROM information_schema.table_constraints AS c
JOIN information_schema.constraint_column_usage AS cc
USING (table_schema, table_name, constraint_name)
WHERE c.constraint_type = 'UNIQUE'
GROUP BY table_schema, table_name
HAVING count(*) = 1;