如何用 apostrophe/single 引号替换逗号?

How to replace comma with apostrophe/single quote?

如何在 pgsql select 查询中用 apostrophe/single 引号替换逗号? 我当前的查询是:

SELECT array_to_string(array_agg(districtname), ', ') as dnames
FROM districts
where id in ('' || Replace((select districtIds from tblmtr where id = 1), ',' , ''',''') || '');

它正在返回 null。
table tblmtr 中的 ID 是这样的 2,3,4

当我将其更改为仅 234 时,它 returns 是正确的结果。
结果应该是这样的:district1name,district2name,district3name

这里有几件事并不理想:

  • 升级到 Postgres 的现代版本Version 8.4 reached EOL in 2014.

  • 看看 database normalization 并重新考虑您的关系设计。在逗号分隔的字符串中存储多个 ID 值通常是一个非常的坏主意。

  • IN 期望 subquery or a list of values。您似乎试图提供一个包含值的字符串,但这是行不通的。考虑使用 JOIN 而不是笨拙的 IN 结构。

虽然坚持你不幸的设计,但将逗号分隔的字符串即时转换为数组并使用 ANY construct.
你忽略了提供你的 table 定义,所以做了一些假设。

SELECT array_to_string(array_agg(d.districtname), ', ') AS dnames
FROM   tblmtr    t 
JOIN   districts d ON d.id = ANY (string_to_array(t.districtIds, ','))
WHERE  t.id = 1;

或者:

SELECT ARRAY (
   SELECT d.districtname
   FROM   tblmtr    t 
   JOIN   districts d ON d.id = ANY (string_to_array(t.districtIds, ','))
   WHERE  t.id = 1
   ) AS dnames;