问题
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