PostgreSQL 查看表结构、主键(多个)

最近在优化代码的时候,想直接通过数据库去了解一张表的结构信息,而不是通过代码去手写表的信息。在网上查阅的资料都只能查出一张表的一个主键(我的数据库有些表是多个主键维护的),最后还是把不同的解决方法组合起来,解决了既能查看表结构,也能查看多个主键。下面是SQL语句:

SELECT
   A.ordinal_position,
   A.column_name,
   CASE A.is_nullable WHEN 'NO' THEN 0 ELSE 1 END AS is_nullable,
   A.data_type,
   coalesce(A.character_maximum_length, A.numeric_precision, -1) as length,
   A.numeric_scale,
        CASE WHEN length(B.attname) > 0 THEN 1 ELSE 0 END AS is_pk
FROM
   information_schema.columns A
LEFT JOIN (
    SELECT
        pg_attribute.attname
    FROM
        pg_index,
        pg_class,
        pg_attribute
    WHERE
        pg_class.oid = '表名' :: regclass
    AND pg_index.indrelid = pg_class.oid
    AND pg_attribute.attrelid = pg_class.oid
    AND pg_attribute.attnum = ANY (pg_index.indkey)
) B ON A.column_name = b.attname
WHERE
   A.table_schema = 'public'
AND A.table_name = '表名'
ORDER BY
   ordinal_position ASC;

你可能感兴趣的:(PostgreSQL)