我的SQL查询结果如下:
ID Col1 Col2
1 xsy 4,5,6
2 abc 4
3 hello 5,4
我想过滤搜索字符串也通过逗号分隔符&的结果。应该在所有情况下匹配col2。
如搜索字符串为4,则应返回第1,2行和第1行。 3.如果搜索字符串为5,则应返回第1行和第1行。 3。
如果我用逗号4,5传递多个搜索条件,它应返回第1,2和1行。 3因为所有这些行都有一个匹配的数字
有关如何实现这一目标的任何想法?
答案 0 :(得分:0)
在列值之前和之后添加逗号(以处理第一个和最后一个项目),然后搜索“逗号值逗号”:
select * from tablename where ',' || col2 || ',' like '%,4,%'
||是用于concat的ANSI SQL。
但是你应该以适当的方式重新设计数据库和存储值!!!
执行时输出:
SQL>create table tso (id int, col1 varchar(10), col2 varchar(10));
SQL>insert into tso values (1,'xsy','4,5,6');
SQL>insert into tso values (2,'abc','4');
SQL>insert into tso values (3,'hello','5,4');
SQL>select * from tso where ',' || col2 || ',' like '%,4,%';
id col1 col2
=========== ========== ==========
1 xsy 4,5,6
2 abc 4
3 hello 5,4
3 rows found
SQL>insert into tso values (4,'extra','5,14');
SQL>insert into tso values (5,'extra','54,41');
SQL>select * from tso where ',' || col2 || ',' like '%,4,%';
id col1 col2
=========== ========== ==========
1 xsy 4,5,6
2 abc 4
3 hello 5,4
3 rows found
另一个例子:
SQL>select * from tso where ',' || col2 || ',' like '%,4,%'
SQL& and ',' || col2 || ',' like '%,5,%';
id col1 col2
=========== ========== ==========
1 xsy 4,5,6
3 hello 5,4
2 rows found
SQL>select * from tso where ',' || col2 || ',' like '%,4,%'
SQL& or ',' || col2 || ',' like '%,5,%';
id col1 col2
=========== ========== ==========
1 xsy 4,5,6
2 abc 4
3 hello 5,4
4 extra 5,14
4 rows found
答案 1 :(得分:0)
这个数据模型非常糟糕,将来会给你带来很多痛苦。如果可能,您应该为col2值引入详细信息表。
但是,如果您绝对无法更改数据模型,可以采用以下方法:
IN
列表仅过滤出您想要的值GROUP BY
和HAVING
来获取具有您想要的所有值的行使用Oracle语法:
with v_data(id, col1, col2) as (
select 1, 'xsy', '4,5,6' from dual union all
select 2, 'abc', '4' from dual union all
select 3, 'hello', '5,4' from dual union all
select 4, 'hi', '45,511' from dual
),
v_data_with_numbers as (
select id, col1, col2,
regexp_substr(col2, '[[:digit:]]+', 1, level) as val
from v_data
connect by level <= 3
),
v_distinct_data_with_numbers as (
select distinct id, col1, col2, val
from v_data_with_numbers
where val is not null
order by id, col1, col2, val
)
select id, col1, col2
from v_distinct_data_with_numbers
where val in (4,5)
group by id, col1, col2
having count(distinct val) = 2 -- require both 4 and 5 to be present; omitting this line will give you all rows that have either one present
答案 2 :(得分:0)
请再试一次这样
select *
from TABLENAME f
where 'searchvalue' = ANY (string_to_array(COLOUMNNAME,','))
示例
select *
from customer f
where '11' = ANY (string_to_array(customerids,','))
答案 3 :(得分:-1)
试试这个
Select * from table_name where col2 like "4"