Using LIKE in an Oracle IN clause

2019-01-12 05:56发布

I know I can write a query that will return all rows that contain any number of values in a given column, like so:

Select * from tbl where my_col in (val1, val2, val3,... valn)

but if val1, for example, can appear anywhere in my_col, which has datatype varchar(300), I might instead write:

select * from tbl where my_col LIKE '%val1%'

Is there a way of combing these two techniques. I need to search for some 30 possible values that may appear anywhere in the free-form text of the column.

Combining these two statements in the following ways does not seem to work:

select * from tbl where my_col LIKE ('%val1%', '%val2%', 'val3%',....) 

select * from tbl where my_col in ('%val1%', '%val2%', 'val3%',....)

8条回答
唯我独甜
2楼-- · 2019-01-12 06:12

Yes, you can use this query:

  SELECT * FROM RandomTable rt 
    WHERE EXISTS (select 1 from table(sys.dbms_debug_vc2coll(//INSERT STRINGS SEPARATED BY COMMA HERE)) as MemoryTable mt where rt.name like mt.column_value);

This way you don't have to create a table.

查看更多
小情绪 Triste *
3楼-- · 2019-01-12 06:16

No, you cannot do this. The values in the IN clause must be exact matches. You could modify the select thusly:

SELECT *
  FROM tbl
 WHERE my_col LIKE %val1%
    OR my_col LIKE %val2%
    OR my_col LIKE %val3%
 ...

If the val1, val2, val3... are similar enough, you might be able to use regular expressions in the REGEXP_LIKE operator.

查看更多
该账号已被封号
4楼-- · 2019-01-12 06:26
select * from tbl
 where exists (select 1 from all_likes where all_likes.value = substr(tbl.my_col,0, length(tbl.my_col)))
查看更多
爷的心禁止访问
5楼-- · 2019-01-12 06:27

Just to add on @Lukas Eder answer.

An improvement to avoid creating tables and inserting values (we could use select from dual and unpivot to achieve the same result "on the fly"):

with all_likes as  
(select * from 
    (select '%val1%' like_1, '%val2%' like_2, '%val3%' like_3, '%val4%' as like_4, '%val5%' as like_5 from dual)
    unpivot (
     united_columns for subquery_column in ("LIKE_1", "LIKE_2", "LIKE_3", "LIKE_4", "LIKE_5"))
  )
    select * from tbl
    where exists (select 1 from all_likes where tbl.my_col like all_likes.united_columns)
查看更多
我想做一个坏孩纸
6楼-- · 2019-01-12 06:31
select * from tbl 
where my_col like '%val1%' or my_col like'%val2%' or my_col like '%val3%', ...

But beware, that might be quite slow... Alternatively, you could insert all acceptable values (including % signs) into a table and semi-join that table:

select * from tbl
where exists (select 1 from all_likes where tbl.my_col like all_likes.value)

For true full-text search, you might want to look at Oracle Text:

http://www.oracle.com/technetwork/database/enterprise-edition/index-098492.html

查看更多
地球回转人心会变
7楼-- · 2019-01-12 06:32

This one is pretty fast :

select * from listofvalue l 
inner join tbl on tbl.mycol like '%' || l.value || '%'
查看更多
登录 后发表回答