如何在Oracle中搜索逗号分隔的数据库列

问题描述 投票:0回答:1

我有一个Oracle DB表,其中一列包含逗号分隔的值(不是我的设计!)。在Web应用程序中,当用户尝试添加导致在该表中添加新条目的对象时,我正在尝试检查是否存在重复项。

我知道如何检查单个值(例如,尝试添加“ ABC”),但是如果用户要添加ABC,DEF,GHI等,则不确定如何执行此操作...

假设表称为PRINTER_MAPPING_CFG,相关列称为RUNOUTS。典型的行可能看起来像:

001, 002, 006, 008, 009

我使用以下命令检查单个值:

SELECT COUNT(*) 
FROM PRINTER_MAPPING_CFG 
WHERE ',' || RUNOUTS || ',' LIKE '%,' || '001' || ',%'

如果用户要添加003、004、006、007、008,我不确定如何继续(此处已经有006和008)。

我可以拆分并分别搜索每个对象,但如果有其他选择,则看起来很浪费。

search oracle12c
1个回答
0
投票

对,不是人们能想到的最佳设计。

看看是否有帮助:

SQL> with
  2  printer_mapping_cfg (id, runouts) as
  3    -- this is what you currently have. I included the ID column
  4    -- as you probably don't have just one row in that table, do you?
  5    (select 1, '001, 002, 006, 008, 009' from dual union all
  6     select 2, '005, 006, 007'           from dual
  7    ),
  8  new_value (runouts) as
  9    -- this is what user enters
 10    (select '003, 004, 006, 007, 008' from dual),   --> 006 and 008 exist for ID = 1
 11  split_pmc as                                      --> 006 and 007 exist for ID = 2
 12    (select p.id,
 13            trim(regexp_substr(p.runouts, '[^,]+', 1, column_value)) val
 14     from printer_mapping_cfg p cross join
 15         table(cast(multiset(select level
 16                             from dual
 17                             connect by level <= regexp_count(p.runouts, ',') + 1
 18                            ) as sys.odcinumberlist))
 19    )
 20  select s.id,
 21         listagg(s.val, ', ') within group (order by s.val) duplicates
 22  from split_pmc s
 23  where s.val in (select trim(regexp_substr(n.runouts, '[^,]+', 1, level))
 24                  from new_value n
 25                  connect by level <= regexp_count(n.runouts, ',') + 1
 26                 )
 27  group by s.id
 28  order by s.id;

        ID DUPLICATES
---------- ------------------------------
         1 006, 008
         2 006, 007

SQL>

它做什么?

  • 第1-7行代表您已经拥有的数据
  • 第8-10行是输入字符串,用户输入的字符串
  • 第11-19行用于将现有值拆分为行
  • #20-28行代表最终的select,其中
    • 第23-26行,检查我们在split_pmc CTE中找到的值是否存在于新添加的值中(这些值已经拆分为行)
    • 第21行将重复的值聚合到单个字符串中

[编辑]

由于您已经有了PRINTER_MAPPING_CFG表,您的代码将以]开头

SQL> with
  2  new_value (runouts) as ...

您仍然像我一样引用PRINTER_MAPPING_CFG表。

将在第18行的某处(在我上面发布的代码中)添加其他条件。

© www.soinside.com 2019 - 2024. All rights reserved.