mateusvl
mateusvl

Reputation: 141

Is it possible to share the same filter parameters (WHERE CLAUSE) with two more fields in SQL?

Consider below

SELECT * FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
WHERE 
t1.A NOT IN ('111111','222222','33333')
AND 
t2.B NOT IN ('111111','222222','33333')

Is there another way to use the same filter parameters for two different fields?

Something like that

SELECT * FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
WHERE (t1.A and t2.B) NOT IN ('111111','222222','33333')

Seems pretty simple, but I couldn't find anything in the docs.

Upvotes: 2

Views: 48

Answers (2)

sticky bit
sticky bit

Reputation: 37472

A CTE would be one possibility.

WITH cte
AS
(
SELECT c
       FROM (VALUES ('111111'),
                    ('222222'),
                    ('33333')) v
                               (c)
)
SELECT *
       FROM table1 t1
            LEFT JOIN table2 t2
                      ON t1.id = t2.id
       WHERE t1.a NOT IN (SELECT c
                                 FROM cte)
             AND t2.c NOT IN (SELECT c
                                     FROM cte);

Upvotes: 2

Mureinik
Mureinik

Reputation: 311228

You could use the array intersection operator (&&) to simulate that condition - create an array of the columns and an array of the values to test, and have a where clause that checks there's no intersection between them:

SELECT    * 
FROM      table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
WHERE     NOT ARRAY[t1.A, t2.B] && ARRAY['111111', '222222', '33333']

Upvotes: 3

Related Questions