2016-12-28 63 views
0

我是PostgreSQL的新手,但到目前爲止,只有教程介紹如何將帶有標題的整個表導出爲.csv。我只想導出字段名稱。僅將Postgres表中的列名導出爲CSV

如何寫一個查詢來僅將表x的列名導出爲.csv?

+0

這不是重複 –

回答

0
COPY (select * from table_name where false) -- To return result without rows 
TO 'D:\File.csv' DELIMITER ',' CSV HEADER; 

create temp table tmp (like table_name); -- To copy structure into a new temp table 
COPY tmp TO 'D:/File.csv' DELIMITER ',' CSV HEADER; 
drop table tmp; 
+0

謝謝,但我沒有一個名爲列'product_id' ... –

+0

哦,我看到,'product_id'是唯一的關鍵 –

0

你應該知道,從psql控制檯,您可以問表結構的一些有用的信息與\d命令。

當然,我明白你需要的是用你的應用程序執行的SQL查詢來檢索信息。

但是,如果你打電話psql-E(或--echo-hidden),然後,輸入\d some table(或任何其他控制檯命令)後,它也將輸出查詢(或查詢)來獲取這些信息。這在這種情況下非常有用。

例如:

test=> \d foo 
********* QUERY ********** 
SELECT c.oid, 
    n.nspname, 
    c.relname 
FROM pg_catalog.pg_class c 
    LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace 
WHERE c.relname ~ '^(foo)$' 
    AND pg_catalog.pg_table_is_visible(c.oid) 
ORDER BY 2, 3; 
************************** 

********* QUERY ********** 
SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, c.relhastriggers, c.relhasoids, '', c.reltablespace, CASE WHEN c.reloftype = 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END, c.relp 
ersistence, c.relreplident 
FROM pg_catalog.pg_class c 
LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid) 
WHERE c.oid = '41967'; 
************************** 

********* QUERY ********** 
SELECT a.attname, 
    pg_catalog.format_type(a.atttypid, a.atttypmod), 
    (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128) 
    FROM pg_catalog.pg_attrdef d 
    WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), 
    a.attnotnull, a.attnum, 
    (SELECT c.collname FROM pg_catalog.pg_collation c, pg_catalog.pg_type t 
    WHERE c.oid = a.attcollation AND t.oid = a.atttypid AND a.attcollation <> t.typcollation) AS attcollation, 
    NULL AS indexdef, 
    NULL AS attfdwoptions 
FROM pg_catalog.pg_attribute a 
WHERE a.attrelid = '41967' AND a.attnum > 0 AND NOT a.attisdropped 
ORDER BY a.attnum; 
************************** 

[...more...] 

現在,第三個查詢與第一個結合是很容易建立只是你想要什麼:

SELECT a.attname 
FROM pg_catalog.pg_attribute a 
WHERE a.attrelid = (
    SELECT c.oid 
    FROM pg_catalog.pg_class c 
    WHERE c.relname ~ '^(foo)$' 
) 
AND a.attnum > 0 AND NOT a.attisdropped 
ORDER BY a.attnum; 

其實,你也可以改變WHERE c.relname ~ '^(foo)$'也有WHERE c.relname = 'foo'。除非您希望能夠通過正則表達式匹配表名稱。我認爲這不是你的情況。

+0

感謝您的信息! –