sql - 如何在选定的字符串中查找数字?
问题描述
我正在尝试在字符串中查找多个数字。
ID | 字符串 1 | 字符串 2 |
---|---|---|
1 | 100,101,201 | 1,2,3,4 |
2 | 100,103,201 | 1,4,9,10 |
3 | 101,102,200 | 1,3,4,10 |
例如,我想获取包含的行 idSTRING1(100,201) AND STRING2(1,4)
结果:ID 1 和 ID 2
解决方案
这是一种方法 - 使事物井井有条,以便于维护。我假设 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
推荐阅读
- java - 在 @Application bean 中使用构造函数注入会导致循环引用
- javascript - 如何选择一个将数组作为其构造函数的一部分的对象?
- nginx - 如何使用 Ingress Controller 在 Kubernetes 中路由请求和平衡负载?
- android - 失败的模拟器依赖
- shake-build-system - 在 Shake 中,Rules 的定义顺序重要吗?
- vue.js - Vue i18n,如何获取 dateTimeLocalization 的语言环境?
- c++ - 如何在成员函数内将函数及其参数传递给 std::async
- android - 如何保存片段数据以显示给下次登录
- python - How I can write the format of my date when I use apply and datetime functions?
- html - 当我减小浏览器大小时,为什么“lounge-mobile.css”样式表没有链接?