In PostgreSQL how to combine NOT IN and LIKE?

白昼怎懂夜的黑 提交于 2019-12-24 09:36:38

问题


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:


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 (...)


来源:https://stackoverflow.com/questions/16854442/in-postgresql-how-to-combine-not-in-and-like

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!