Using LIKE in an Oracle IN clause

前端 未结 9 1542
情深已故
情深已故 2020-12-06 09:49

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, v         


        
相关标签:
9条回答
  • 2020-12-06 10:02

    Yes, you can use this query (Instead of 'Specialist' and 'Developer', type any strings you want separated by comma and change employees table with your table)

    SELECT * FROM employees em
        WHERE EXISTS (select 1 from table(sys.dbms_debug_vc2coll('Specialist', 'Developer')) mt where em.job like ('%' || mt.column_value || '%'));
    

    Why my query is better than the accepted answer: You don't need a CREATE TABLE permission to run it. This can be executed with just SELECT permissions.

    0 讨论(0)
  • 2020-12-06 10:14

    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)
    
    0 讨论(0)
  • 2020-12-06 10:16

    This one is pretty fast :

    select * from listofvalue l 
    inner join tbl on tbl.mycol like '%' || l.value || '%'
    
    0 讨论(0)
  • 2020-12-06 10:16
    select * from tbl
     where exists (select 1 from all_likes where all_likes.value = substr(tbl.my_col,0, length(tbl.my_col)))
    
    0 讨论(0)
  • 2020-12-06 10:16

    I prefer this

    WHERE CASE WHEN my_col LIKE '%val1%' THEN 1    
               WHEN my_col LIKE '%val2%' THEN 1
               WHEN my_col LIKE '%val3%' THEN 1
               ELSE 0
               END = 1
    

    I'm not saying it's optimal but it works and it's easily understood. Most of my queries are adhoc used once so performance is generally not an issue for me.

    0 讨论(0)
  • 2020-12-06 10:17

    You can put your values in ODCIVARCHAR2LIST and then join it as a regular table.

    select tabl1.* FROM tabl1 LEFT JOIN 
    (select column_value txt from table(sys.ODCIVARCHAR2LIST
    ('%val1%','%val2%','%val3%')
    )) Vals ON tabl1.column LIKE Vals.txt WHERE Vals.txt IS NOT NULL
    
    0 讨论(0)
提交回复
热议问题