将postgres表列中以逗号分隔的值列表转换为in子句中使用的值



在一个名为all_fruits的postgres表中,我存储了以下文本列数据,其中用逗号分隔:

Column fruit_name =apples, oranges, pears

我想使用这个列数据作为select IN查询的一部分,即:

select countries
from   all_countries
where  fruit in (select fruit_name from all_fruits where fruit_id = 123);

我的问题是,我如何在postgres转换这个逗号分隔的水果列表(fruit_name)显示如下,每个单独的水果名称周围的单引号:

列fruit_name ='apples', 'oranges', 'pears',以便我可以在上面的IN子句中使用?

正确的解决方案是规范化您的数据模型,而不是存储逗号分隔的值。

但是如果你不能修复你的模型,你需要解开这些值:

select countries
from all_countries
where fruit in (select f.name 
from all_fruits af
cross join unnest(string_to_array(af.fruit_name, ',')) as f(name)
where af.fruit_id = 123
)

最新更新