PostgreSQL,获取列名,列类型和描述

KuK*_*KeC 3 postgresql

我想为选定架构中的选定表获得所需的结果,像这样

column_name  |  data_type   | description
-----------------------------------------
id           | integer      |  id of bill
name         | character    |
address      | character    | adress of buyer
Run Code Online (Sandbox Code Playgroud)

请注意,有些列没有描述(列注释)。

现在,我只得到了这个查询,它给我很好的结果,但只得到了带有注释的列(对于所选表中没有注释的列,则不会在输出中显示)。

我的查询仅返回具有注释的列的数据

SELECT c.column_name, c.data_type, pgd.description 
from pg_catalog.pg_statio_all_tables as st 
inner join pg_catalog.pg_description pgd on (pgd.objoid=st.relid) 
inner join information_schema.columns c on (pgd.objsubid=c.ordinal_position and  c.table_schema=st.schemaname and c.table_name=st.relname)  
where table_schema = 'public' and table_name = 'some_table';
Run Code Online (Sandbox Code Playgroud)

如何获取没有评论的列?

kli*_*lin 5

有功能 col_description(table_oid, column_number)

select column_name, data_type, col_description('public.my_table'::regclass, ordinal_position)
from information_schema.columns
where table_schema = 'public' and table_name = 'my_table';

 column_name | data_type |  col_description  
-------------+-----------+-------------------
 gid         | integer   | a comment for gid
 id          | integer   | 
 max_height  | numeric   | 
(3 rows)
Run Code Online (Sandbox Code Playgroud)


Vao*_*sun 4

因为information_schema.columns该表肯定包含数据,并且您不是第一个引用它,right outer join所以您需要:

t=# SELECT c.column_name, c.data_type, pgd.description
from pg_catalog.pg_statio_all_tables as st
inner join pg_catalog.pg_description pgd on (pgd.objoid=st.relid)
right outer join information_schema.columns c on (pgd.objsubid=c.ordinal_position and  c.table_schema=st.schemaname and c.table_name=st.relname)
where table_schema = 'public' and table_name = 's150';
  column_name  | data_type | description
---------------+-----------+-------------
 customer_name | text      |
 order_id      | text      |
 order_date    | date      |
(3 rows)
Run Code Online (Sandbox Code Playgroud)