How to use same list twice in WHERE clause?

梦想的初衷 提交于 2019-12-23 09:47:27

问题


My SQL query contains a WHERE clause looking like this:

WHERE 
      name1 in ('Emily', 'Jack', 'James', 'Chloe') 
   OR name2 in ('Emily', 'Jack', 'James', 'Chloe')

Note that the same list appears twice, which is quite unsatisfying (and my real list is actually longer).

What would be a better way to write this query?


回答1:


You can use arrays and overlap operator &&, e.g.:

with my_table(name1, name2) as (
values ('Emily', 'Bob'), ('Ben', 'Jack'), ('Bob', 'Ben')
)

select *
from my_table
where array[name1, name2] && array['Emily', 'Jack', 'James', 'Chloe'];

 name1 | name2 
-------+-------
 Emily | Bob
 Ben   | Jack
(2 rows)



回答2:


Use a common table expression:

with to_check (name) as (
   values ('Emily'), ('Jack'), ('James'), ('Chloe') 
)
select ...
from ...
WHERE name1 in (select name from to_check) 
   OR name2 in (select name from to_check);



回答3:


One method is regular expressions:

WHERE (name1 || ' ' || name2) ~ 'Emily|Jack|James|Chloe'

This isn't exactly the same logic (the name "Emily Doe" would match this logic but not the first), but it might do what you want.



来源:https://stackoverflow.com/questions/42694612/how-to-use-same-list-twice-in-where-clause

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