PostgreSQL“DESCRIBE TABLE”

如何在 PostgreSQL 中执行等效于 Oracle DESCRIBE TABLE的命令(使用 psql 命令)?

答案

试试看(在psql命令行工具中):

\d+ tablename

有关更多信息,请参见手册

除了 PostgreSQL 方式(\ d'something' 或 \ dt'table' 或 \ ds'sequence' 等)

SQL 标准的方式,如图所示在这里

select column_name, data_type, character_maximum_length
from INFORMATION_SCHEMA.COLUMNS where table_name = '<name of table>';

许多数据库引擎都支持它。

如果要从查询而不是 psql 获取它,则可以查询目录架构。这是一个执行此操作的复杂查询:

SELECT  
    f.attnum AS number,  
    f.attname AS name,  
    f.attnum,  
    f.attnotnull AS notnull,  
    pg_catalog.format_type(f.atttypid,f.atttypmod) AS type,  
    CASE  
        WHEN p.contype = 'p' THEN 't'  
        ELSE 'f'  
    END AS primarykey,  
    CASE  
        WHEN p.contype = 'u' THEN 't'  
        ELSE 'f'
    END AS uniquekey,
    CASE
        WHEN p.contype = 'f' THEN g.relname
    END AS foreignkey,
    CASE
        WHEN p.contype = 'f' THEN p.confkey
    END AS foreignkey_fieldnum,
    CASE
        WHEN p.contype = 'f' THEN g.relname
    END AS foreignkey,
    CASE
        WHEN p.contype = 'f' THEN p.conkey
    END AS foreignkey_connnum,
    CASE
        WHEN f.atthasdef = 't' THEN d.adsrc
    END AS default
FROM pg_attribute f  
    JOIN pg_class c ON c.oid = f.attrelid  
    JOIN pg_type t ON t.oid = f.atttypid  
    LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum  
    LEFT JOIN pg_namespace n ON n.oid = c.relnamespace  
    LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)  
    LEFT JOIN pg_class AS g ON p.confrelid = g.oid  
WHERE c.relkind = 'r'::char  
    AND n.nspname = '%s'  -- Replace with Schema name  
    AND c.relname = '%s'  -- Replace with table name  
    AND f.attnum > 0 ORDER BY number
;

它非常复杂,但是它确实向您展示了 PostgreSQL 系统目录的功能和灵活性,并且应该使您逐渐掌握 pg_catalog ;-)。确保更改查询中的%s。第一个是模式,第二个是表名。

您可以使用 psql 斜杠命令执行此操作:

\d myTable describe table

它也适用于其他对象:

\d myView describe view
 \d myIndex describe index
 \d mySequence describe sequence

资料来源: faqs.org

DESCRIBE TABLE的 psql 等效项是\d table

有关更多详细信息,请参见 PostgreSQL 手册的 psql 部分。

您可以使用星号 \d *search pattern *来查找与您感兴趣的搜索模式匹配的表。

这应该是解决方案:

SELECT * FROM information_schema.columns
WHERE table_schema = 'your_schema'
   AND table_name   = 'your_table'

除了已经找到的命令行\d+ <table_name> ,您还可以使用info -schema使用info_schema.columns 查找信息。

SELECT *
FROM info_schema.columns
WHERE table_schema = 'your_schema'
AND table_name   = 'your_table'

您可以使用:

SELECT attname 
FROM pg_attribute,pg_class 
WHERE attrelid=pg_class.oid 
AND relname='TableName' 
AND attstattarget <>0;

使用以下 SQL 语句

SELECT DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE table_name = 'tbl_name' 
AND COLUMN_NAME = 'col_name'

如果替换 tbl_name 和 col_name,它将显示您要查找的特定列的数据类型。