如何在 PostgreSQL 中提取 table 的唯一列的名称?
How to extract the names of unique columns of a table in PostgreSQL?
假设我在 PorstreSQL 中有一个 table 定义为:
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
查询应该同时忽略多个列的唯一键。
您需要 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;
假设我在 PorstreSQL 中有一个 table 定义为:
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
查询应该同时忽略多个列的唯一键。
您需要 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;