【问题标题】:How to find numbers inside selected string?如何在选定的字符串中查找数字?
【发布时间】:2021-11-10 16:57:47
【问题描述】:

我正在尝试在字符串中查找多个数字。

ID STRING1 STRING2
1 100,101,201 1,2,3,4
2 100,103,201 1,4,9,10
3 101,102,200 1,3,4,10

例如,我想获取包含STRING1(100,201) AND STRING2(1,4)的行ID

结果:ID 1 和 ID 2

【问题讨论】:

    标签: sql oracle plsql oracle-sqldeveloper


    【解决方案1】:

    这是一种方法 - 使事物井井有条,以便于维护。我假设 Oracle 12.1 或更高版本,所以我可以使用 JSON 函数(快速拆分列表);在旧版本中,您必须以不同的方式编写函数,但概念是相同的。

    这个想法是编写一个函数来拆分数字列表并返回一个嵌套表。您需要一个全局(模式级别)类型,所以我先定义它,然后定义函数。然后我展示了一个示例表(您与我们共享的那个)以及查询的样子。

    创建架构级类型和辅助函数

    create or replace type tbl_of_num is table of number;
    /
    
    create or replace function str_to_tbl(s varchar2)
      return tbl_of_num
      deterministic
    is
      pragma udf;
      ton tbl_of_num;
    begin
      select cast(collect(val) as tbl_of_num)
        into ton
        from json_table('[' || s || ']', '$[*]' columns val number path '$');
      return ton;
    end;
    /
    

    为测试创建小表

    create table t (id, string1, string2) as
        select 1, '100,101,201', '1,2,3,4'  from dual union all
        select 2, '100,103,201', '1,4,9,10' from dual union all
        select 3, '101,102,200', '1,3,4,10' from dual
    ;
    

    示例查询

    首先我定义了两个绑定变量,并初始化它们。这就是您在 SQL*Plus 中的做法;您可能有其他方式将值传递给绑定变量(取决于您的应用程序、用户界面等)

    variable string1 varchar2(100)
    variable string2 varchar2(100)
    
    exec :string1 := '100,201'; :string2 := '1,4'
    

    查询和输出:

    select id
    from   t
    where  str_to_tbl(:string1) submultiset of str_to_tbl(string1)
      and  str_to_tbl(:string2) submultiset of str_to_tbl(string2)
    ;
    
    
            ID
    ----------
             1
             2
    

    【讨论】:

      【解决方案2】:

      这是一个可怕的数据模型。一种方法使用like

      select t.*
      from t
      where ',' || string1 || ',' like '%,100,%' and
            ',' || string1 || ',' like '%,201,%' and
            ',' || string2 || ',' like '%,1,%' and
            ',' || string2 || ',' like '%,4,%' ;
       
      
       
      

      【讨论】:

      • 感谢您的回复戈登!不幸的是我不对模型负责:(我忘了添加一些东西......数字的数量是动态的。有时string1有时可以得到一个数字3。string2也是如此:(
      • 以上就是为什么您必须考虑一下您发布的测试数据。您应该至少有一个具有不同条目数的示例。请记住,社区只知道您发布的内容。不要假设我们了解您的数据,请举例说明。
      猜你喜欢
      • 1970-01-01
      • 2023-01-23
      • 1970-01-01
      • 2022-12-02
      • 2017-03-22
      • 2015-08-06
      • 1970-01-01
      • 2021-12-22
      相关资源
      最近更新 更多