如何在PostgreSQL中提取表的唯一列的名称?

问题描述 投票:0回答:1

假设我在PorstreSQL中有一个表定义为:

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个回答
1
投票

您需要information_schema.table_constraintsinformation_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;
© www.soinside.com 2019 - 2024. All rights reserved.