searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

pg数据库查询表结构基本sql

2025-01-07 09:29:08
4
0

根据模式名查询该模式下所有表的字段名称等信息

SELECT
    pc.relname AS table_name,
    pa.attname AS column_name,
    pt.typname AS column_type,
    ( CASE WHEN pa.attlen > 0 THEN pa.attlen ELSE pa.atttypmod - 4 END ) AS column_length,
    pa.attnotnull AS is_null,
    (    CASE WHEN ( SELECT COUNT(*) FROM pg_constraint WHERE conrelid = pa.attrelid AND conkey[1]= attnum AND contype = 'p' ) > 0 THEN
        TRUE ELSE FALSE 
        END ) AS is_primary,
        pd.description AS comment
    FROM
        pg_class pc,
        pg_attribute pa,
        pg_type pt,
        pg_description pd 
    WHERE
        pc.oid = pa.attrelid 
        AND pt.oid = pa.atttypid 
        AND pd.objoid = pa.attrelid 
        AND pd.objsubid = pa.attnum 
        AND pc.relname in (SELECT tablename
FROM pg_tables
WHERE schemaname = 'xxx_table') 
    ORDER BY
        pc.relname DESC,
        pa.attnum ASC
0条评论
作者已关闭评论
孟****寅
55文章数
0粉丝数
孟****寅
55 文章 | 0 粉丝
原创

pg数据库查询表结构基本sql

2025-01-07 09:29:08
4
0

根据模式名查询该模式下所有表的字段名称等信息

SELECT
    pc.relname AS table_name,
    pa.attname AS column_name,
    pt.typname AS column_type,
    ( CASE WHEN pa.attlen > 0 THEN pa.attlen ELSE pa.atttypmod - 4 END ) AS column_length,
    pa.attnotnull AS is_null,
    (    CASE WHEN ( SELECT COUNT(*) FROM pg_constraint WHERE conrelid = pa.attrelid AND conkey[1]= attnum AND contype = 'p' ) > 0 THEN
        TRUE ELSE FALSE 
        END ) AS is_primary,
        pd.description AS comment
    FROM
        pg_class pc,
        pg_attribute pa,
        pg_type pt,
        pg_description pd 
    WHERE
        pc.oid = pa.attrelid 
        AND pt.oid = pa.atttypid 
        AND pd.objoid = pa.attrelid 
        AND pd.objsubid = pa.attnum 
        AND pc.relname in (SELECT tablename
FROM pg_tables
WHERE schemaname = 'xxx_table') 
    ORDER BY
        pc.relname DESC,
        pa.attnum ASC
文章来自个人专栏
行业动态-mdy
55 文章 | 1 订阅
0条评论
作者已关闭评论
作者已关闭评论
0
0