连字符表名称周围的双引号失败

时间:2018-06-08 00:12:41

标签: postgresql

我们使用SaaS软件从云端提取营销数据。当我尝试将查询结果转储到CSV文件时如此

psql my.server -p 5432 -U myuser -d mydb -c "\copy (SELECT 
c.*,cip.*,cipi.* FROM saas.contacts c LEFT JOIN 
saas."contacts__identity-profiles" cip ON 
cip."_sdc_source_key_vid" = c.vid LEFT JOIN 
saas."contacts__identity-profiles__identities" cipi ON 
cipi."_sdc_source_key_vid" = cip."_sdc_source_key_vid" AND 
cipi."_sdc_level_0_id" = cip."_sdc_level_0_id") to 
'/tmp/contacts.csv' DELIMITER ',' CSV HEADER "

失败并出现以下错误

ERROR:  syntax error at or near "-"
LINE 1: ...EFT JOIN saas.contacts__identity-profiles ...

我知道Postgres要求我在带连字符的表名称周围添加双引号,但这显然不起作用。我试过了

  • 在表名中转义连字符,如"contacts__identity\-profiles",但无效
  • 在表名周围加倍双引号但无济于事。

问题似乎与在COPY命令中使用双引号有关。我可以用任何方式解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

你有双引号同时做两件事:

  • 外部双引号用于bash将该命令作为一个参数传递给psql
  • 内部双引号用于PostgreSQL,因此您可以引用带连字符的标识符。

您需要转义内部引号以使其通过bash并进入psql

psql my.server -p 5432 -U myuser -d mydb -c "... saas.\"contacts__identity-profiles\" ..."
# ----------------------------------------------------^^ ------------------------- ^^

等等。将它们全部转出(来自bash)会给你:

psql my.server -p 5432 -U myuser -d mydb -c "\copy (SELECT c.*,cip.*,cipi.* FROM saas.contacts c LEFT JOIN saas.\"contacts__identity-profiles\" cip ON cip.\"_sdc_source_key_vid\" = c.vid LEFT JOIN saas.\"contacts__identity-profiles__identities\" cipi ON cipi.\"_sdc_source_key_vid\" = cip.\"_sdc_source_key_vid\" AND cipi.\"_sdc_level_0_id\" = cip.\"_sdc_level_0_id\") to '/tmp/contacts.csv' DELIMITER ',' CSV HEADER "

答案 1 :(得分:-1)

您可以尝试在单引号中输入完整命令,然后在内部使用双引号进行其他用途,如下所示:

psql my.server -p 5432 -U myuser -d mydb -c '\copy (SELECT 
c.*,cip.*,cipi.* FROM saas.contacts c LEFT JOIN 
saas."contacts__identity-profiles" cip ON 
cip."_sdc_source_key_vid" = c.vid LEFT JOIN 
saas."contacts__identity-profiles__identities" cipi ON 
cipi."_sdc_source_key_vid" = cip."_sdc_source_key_vid" AND 
cipi."_sdc_level_0_id" = cip."_sdc_level_0_id") to 
"/tmp/contacts.csv" DELIMITER "," CSV HEADER '

希望这会有所帮助!!