gpt4 book ai didi

sql - 如何使用 PostgreSQL 从表名中获取列属性查询?

转载 作者:行者123 更新时间:2023-11-29 11:11:31 24 4
gpt4 key购买 nike

我有一个项目,我需要一个查询来获取列的所有属性(列名、位置、数据类型、非空?和注释)所有这些都使用表名。

我实现了获取列名、位置数据类型和非空?使用此查询:

SELECT column_name, data_type, ordinal_position, is_nullable 
FROM information_schema."columns"
WHERE "table_name"='TABLE-NAME'

但是,我需要评论!

最佳答案

这是针对 system catalog 的查询那应该获取您需要的所有内容(免费提供一个额外的主键字段)。

SELECT DISTINCT
a.attnum as num,
a.attname as name,
format_type(a.atttypid, a.atttypmod) as typ,
a.attnotnull as notnull,
com.description as comment,
coalesce(i.indisprimary,false) as primary_key,
def.adsrc as default
FROM pg_attribute a
JOIN pg_class pgc ON pgc.oid = a.attrelid
LEFT JOIN pg_index i ON
(pgc.oid = i.indrelid AND i.indkey[0] = a.attnum)
LEFT JOIN pg_description com on
(pgc.oid = com.objoid AND a.attnum = com.objsubid)
LEFT JOIN pg_attrdef def ON
(a.attrelid = def.adrelid AND a.attnum = def.adnum)
WHERE a.attnum > 0 AND pgc.oid = a.attrelid
AND pg_table_is_visible(pgc.oid)
AND NOT a.attisdropped
AND pgc.relname = 'TABLE_NAME' -- Your table name here
ORDER BY a.attnum;

这将返回如下结果:

 num |    name     |             typ             | notnull |       comment       | primary_key 
-----+-------------+-----------------------------+---------+---------------------+-------------
1 | id | integer | t | a primary key thing | t
2 | ref | text | f | | f
3 | created | timestamp without time zone | t | | f
4 | modified | timestamp without time zone | t | | f
5 | name | text | t | | f
  • num: 列号
  • name: 列名
  • typ:数据类型
  • notnull:列是否定义为NOT NULL
  • comment:为列定义的任何COMMENT
  • primary_key:是否列定义为PRIMARY KEY
  • default: 用于默认值的命令

关于sql - 如何使用 PostgreSQL 从表名中获取列属性查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15928118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com