2017-06-12 110 views
0

我要在選定的模式選擇表得到期望的結果是這樣PostgreSQL的,獲得列名,列類型和描述

column_name | data_type | description 
----------------------------------------- 
id   | integer  | id of bill 
name   | character | 
address  | character | adress of buyer 

注意,有些字段沒有說明(列註釋)。

現在我只拿到了這個查詢,給了我很好的結果,但僅適用於有意見(對於那些在選定表中,並且沒有評論在輸出中沒有代表列)列。

我的查詢這對於有評論列返回唯一數據是下一個

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'; 

如何獲得列沒有結果有何評論?

+0

只是用'LEFT JOIN '。 'INNER JOIN'給你兩個表的交集。如果表A中的行與表B沒有關係,則該行將不會包含在輸出中。 – KarelG

+0

在發佈問題之前嘗試使用左連接,結果仍然相同 – KuKeC

回答

1

因爲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) 
+0

這樣做的竅門。謝謝您的幫助 – KuKeC

2

有功能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)