How to use SQL LIKE condition with multiple values in PostgreSQL?

前端 未结 6 1353
小蘑菇
小蘑菇 2020-12-04 18:03

Is there any shorter way to look for multiple matches:

 SELECT * 
 from table 
 WHERE column LIKE \"AAA%\" 
    OR column LIKE \"BBB%\" 
    OR column LIKE \         


        
相关标签:
6条回答
  • 2020-12-04 18:18

    Perhaps using SIMILAR TO would work ?

    SELECT * from table WHERE column SIMILAR TO '(AAA|BBB|CCC)%';
    
    0 讨论(0)
  • 2020-12-04 18:19

    Following query helped me. Instead of using LIKE, you can use ~*.

    select id, name from hosts where name ~* 'julia|lena|jack';
    
    0 讨论(0)
  • 2020-12-04 18:23

    You can use regular expression operator (~), separated by (|) as described in Pattern Matching

    select column_a from table where column_a ~* 'aaa|bbb|ccc'
    
    0 讨论(0)
  • 2020-12-04 18:25

    Using array or set comparisons:

    create table t (str text);
    insert into t values ('AAA'), ('BBB'), ('DDD999YYY'), ('DDD099YYY');
    
    select str from t
    where str like any ('{"AAA%", "BBB%", "CCC%"}');
    
    select str from t
    where str like any (values('AAA%'), ('BBB%'), ('CCC%'));
    

    It is also possible to do an AND which would not be easy with a regex if it were to match any order:

    select str from t
    where str like all ('{"%999%", "DDD%"}');
    
    select str from t
    where str like all (values('%999%'), ('DDD%'));
    
    0 讨论(0)
  • 2020-12-04 18:32

    You might be able to use IN, if you don't actually need wildcards.

    SELECT * from table WHERE column IN ('AAA', 'BBB', 'CCC')

    0 讨论(0)
  • 2020-12-04 18:38

    Use LIKE ANY(ARRAY['AAA%', 'BBB%', 'CCC%']) as per this cool trick @maniek showed earlier today.

    0 讨论(0)
提交回复
热议问题