In PostgreSQL how to combine NOT IN and LIKE?

2019-08-09 23:03发布

How do you combine NOT IN and LIKE?

Let's assume we have a table that contains a column of names (something like 'blue cheese', 'gouda cheese' and so on) and I want to select all the names that doesn't contain 'cheese', 'milk', 'meat'.

As far as I understand to look for something that is not in an array of strings you use NOT IN and the pass the strings

SELECT names FROM some_table NOT IN('cheese','milk','meat');

but how do I pass

LIKE '%cheese%'

to it?

1条回答
我只想做你的唯一
2楼-- · 2019-08-09 23:32

The construct LIKE ANY (ARRAY[...]) appears to meet your needs;

craig=> SELECT a FROM (
           VALUES ('cheesy'), ('imilk'), ('donut'), ('pie'), ('avocado'), ('meaty')
        ) x(a) 
        WHERE NOT a LIKE ANY (ARRAY['%cheese%','%milk%','%meat%']);

    a    
---------
 cheesy
 donut
 pie
 avocado
(4 rows)

You need the wildcard characters if you want to use LIKE this way. If you really just want equality, you can use:

NOT = ANY (...)
查看更多
登录 后发表回答