首页 > 解决方案 > 在表中查找具有唯一约束的列

问题描述

我正在从 MySQL 迁移到 PostgreSQL。我需要在表中找到所有具有唯一约束的列。PostgreSQL 中以下查询的等价物是什么?

SELECT column_name, index_name
FROM information_schema.statistics
WHERE table_schema='db' and table_name='tb' and non_unique=0 and index_name != 'PRIMARY'

标签: mysqlpostgresql

解决方案


使用 information_schema 的解决方案:

SELECT
    cu.column_name,
    tc.constraint_name
FROM
    information_schema.table_constraints AS tc
JOIN 
    information_schema.constraint_column_usage AS cu 
ON 
    tc.constraint_name = cu.constraint_name
WHERE
    constraint_type = 'UNIQUE'
AND 
    tc.table_catalog = 'db'
AND 
    tc.table_schema = 'public'
AND 
    tc.table_name = 'tb';

推荐阅读