仅将postgres表中的列名导出为CSV

时间:2016-12-28 06:33:18

标签: sql postgresql csv

我是PostgreSQL的新手,但到目前为止,只有关于如何将带有标题的整个表导出到.csv的教程。我想只导出字段名称。

如何编写查询以仅将表x的列名导出为.csv?

3 个答案:

答案 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;

答案 1 :(得分: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'。除非您希望能够通过正则表达式匹配表名。我认为不是你的情况。

答案 2 :(得分:0)

另一种方法,使用命令行中的psql,这样就不需要超级用户权限了

psql -U user -d database -c "COPY (SELECT * FROM table WHERE FALSE) To STDOUT With CSV HEADER DELIMITER ',';" > tmp/foo.csv

仅以逗号分隔的列表返回列名:

$ more tmp/foo.csv
id,name,date,status...