查询不读取存储在表中的引用字符串值

问题描述

我已将一些引用的值存储在单独的表中,并基于此表中的值。我正在尝试过滤另一个表中的行 通过在子查询中使用此表中的值。但它不会读取子查询的值并在输出中返回一个空白表。

该值在 override 列中并解析为 'HCC11','HCC12'

当我只是从列中复制值并将其粘贴到子查询的位置时,它会正确获取数据。我无法理解这里的问题。我在这里尝试使用 trim() 函数,但仍然无法正常工作

注意-:我附上了图片供您参考:

enter image description here

select * 
from table1 
where column1 in (select override  from table 2 )

解决方法

将逗号分隔的值存储在单列中是一个非常糟糕的数据库,一开始将它们括在引号中会使事情变得更糟。解决问题的正确方法是更好的设计。

但是,如果您被迫使用糟糕的设计,您可以使用

将它们转换为正确的值列表
select *
from table1
where column1 in (select trim(both '''' from w.word)
                  from table2 t2
                    cross join unnest(string_to_array(t2.override,',')) as w(word)

这假设 table1.column1 只包含一个没有任何引号的值,并且覆盖值在实际值中从不包含逗号(例如,上面会在像 'A,B','C' 这样的值上中断)

> ,

根据您的图像,table1.column1 的值必须是 'HCC11','HCC12'(一个字符串)才能从子查询中获取匹配项。 如果 table1 有 2 行,其值为 HCC11HCC12,那么您可以在子查询中使用 exists 关键字。 类似的东西

select * 
 from table1 t1 
where exists 
  (select 1 
   from table2 t2 
   where instr( t2.override,concat("'",t1.column1,"'") ) >=1 
  );
,

您将覆盖列值设为 'HCC11','HCC12',该值无法与单个值 'HCC11' 匹配。您最好按如下方式使用 LIKE 运算符:

select *  from table1 t1 
where exists 
  (select 1 from table2 t2 
   where t2.override like concat('%''','''%'));
,

你可以这样做 -

1.

select * from table1
where column1 in 
(select regexp_replace(unnest(string_to_array(override,')),'''','','g') from table2)

2.

select * from table1 
where '''' || column1 || '''' in
(select unnest(string_to_array(override,')) from table2)

虽然,我只是建议不要像这样存储您的数据,因为您想使用它进行查询。