postgresql - postgres 从 regexp_split_to_table 生成的行中选择并抛出错误的位置

标签 postgresql

我有一个表“my_table”,其中有两列 (c1,c2) 以完全相同的格式保存数据“1,2,3,4;5,6,7,8” 我使用 regexp_split_to_table 将它们拆分成行,并尝试选择非空行。

SELECT * from 
 (SELECT '1' as param1 ,'2' as param2, param3 FROM
  ((select regexp_split_to_table(my_table.c1, ';') as param3
   FROM  my_table)
 UNION
  (select regexp_split_to_table(my_table.c2, ';') as param3
   FROM  my_table)) AS a) as b

 where param3 is not null

运行此查询会出现以下错误:

set-valued function called in context that cannot accept a set

如果我删除并集并仅从其中一列中进行选择,或者按其他字段之一 (param1/param2) 进行过滤,则查询有效。 我认为这可能是数据的问题,所以我尝试从同一列中选择两次:

SELECT * from 
 (SELECT '1' as param1 ,'2' as param2, param3 FROM
  ((select regexp_split_to_table(my_table.c1, ';') as param3
   FROM  my_table)
 UNION
  (select regexp_split_to_table(my_table.c1, ';') as param3
   FROM  my_table)) AS a) as b

 where param3 is not null

但我仍然得到同样的错误。 有人知道如何解决这个问题吗? 谢谢!

最佳答案

我建议使用 CTE 而不是子查询并格式化您的查询。这是我认为您需要的查询:

with cte1 as (
  select regexp_split_to_table(t.c1, ';') as param3
  from my_table as t
  union all
  select regexp_split_to_table(t.c2, ';') as param3
  from my_table as t
)
select '1' as param1 ,'2' as param2, c.param3
from cte1 as c
where c.param3 is not null

sql fiddle demo

注意:我不知道您的查询是否需要重复项,所以如果您不需要 - 使用 union 而不是 union all

更新

with cte1 as (
  select regexp_split_to_table(t.c1, ';') as param3
  from my_table as t
  union all
  select regexp_split_to_table(t.c2, ';') as param3
  from my_table as t
), cte2 as (
  select regexp_split_to_table(c.param3, ',') as param3
  from cte1 as c
  where c.param3 is not null and c.param3 <> ''
)
select *
from cte2 as c
where c.param3 is not null and c.param3 <> ''

sql fiddle demo

update2 甚至可以用一个正则表达式来完成

with cte1 as (
    select c1 as param3 from my_table
    union all
    select c2 as param3 from my_table
), cte2 as (
  select regexp_split_to_table(param3, '(;|,)') as param3
  from cte1
)
select '1' as param1 ,'2' as param2, c.param3
from cte2 as c
where nullif(c.param3, '') <> ''

sql fiddle demo

关于postgresql - postgres 从 regexp_split_to_table 生成的行中选择并抛出错误的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18183230/

相关文章:

python - 一段时间后 POSTGIS 插入变慢

sql - 如何对表施加约束以确保表子集中只有一个 bool 列为真?

区域内点的 Hibernate-Spatial 查询

postgresql - 由于 XXXX : unknown migration in database,无法创建迁移计划

python - Postgresql DROP TABLE 不起作用

sql - 如何比较两个 SQL 查询以在 Postgres 上运行

postgresql - Reporting Services - 连接字符串和参数

sql - 使用约束和默认值向现有 PostgreSQL 表添加一列

sql - 如何在postgresql中存储多边形数据?

java - 使用 Spring + 没有为参数指定值调用 Postgres 存储过程