簡體   English   中英

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

[英]How to extract the names of unique columns of a table in PostgreSQL?

假設我在 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

查詢應該一起忽略多個列的唯一鍵。

您需要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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM