SQL query to match one of multiple strings

前端 未结 4 1651
轻奢々
轻奢々 2021-01-04 17:08

I have following data in table:

+----------------------+----------------------------------------------------------+--------------+
| subscriber_fields_id | n         


        
相关标签:
4条回答
  • 2021-01-04 17:27

    You can use this:

    select * from subscriberfields
    where  name like any(array['%Khairpur%','%Islamabad%','%Karachi%']);
    

    https://postgres.cz/wiki/PostgreSQL_SQL_Tricks#LIKE_to_list_of_patterns

    0 讨论(0)
  • 2021-01-04 17:37

    Use OR in WHERE clause, like,

    select * from subscriberfields where name like '%Khairpur%' OR name like '%Islamabad%' OR name like '%Karachi%';
    

    Hope it works.

    0 讨论(0)
  • 2021-01-04 17:40

    Try using SIMILAR TO like below:

    SELECT * FROM subscriberfields 
    WHERE name SIMILAR TO '%(Khairpur|Islamabad|Karachi)%';
    

    Also you should read up on database normalization. Your design could and should definitely be improved.

    0 讨论(0)
  • 2021-01-04 17:49

    For a proper solution, either normalize your database design or, barring that, consider full text search.

    For a quick solution to the problem at hand, use a regular expression match (~) or three simple LIKE expressions:

    SELECT *
    FROM   subscriberfields 
    WHERE  name ~ '(Khairpur|Islamabad|Karachi)';
    

    Or:

    ...
    WHERE (name LIKE '%Khairpur%'
        OR name LIKE '%Islamabad%'
        OR name LIKE '%Karachi%')
    

    Or use ~* or ILIKE for case-insensitive matching.

    Since another answer suggested it: never use SIMILAR TO:

    • Using SIMILAR TO for a regex?
    • Pattern matching with LIKE, SIMILAR TO or regular expressions in PostgreSQL
    0 讨论(0)
提交回复
热议问题