HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Is it possible to write (A OR B) IN(X, Y, ..., W)?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
possiblewritestackoverflow

Problem

Is it possible to write (A OR B) IN(X, Y, ..., W) ?

I need to fill two IN() expr. with same values by hand. Like:

A IN(X, Y, ..., W) OR B IN(X, Y, ..., W)


What is the best option to have only one IN() to fill?

Solution

No, there isn't a simple solution, unless the values are already in respective (normal or temporary) tables. If they are,

A IN(X, Y, ..., W) OR B IN(X, Y, ..., W)


is easy to rewrite. It's equivalent to:

EXISTS ( SELECT * 
         FROM List1 JOIN List2 ON List1.item = List2.item )


If the A and B are not supplied values/parameters but columns/expressions from the tables involved in the query, we can use a mixed approach, having only the X, Y, ..., W values in a (temp) table:

A IN (SELECT item FROM List2) 
OR 
B IN (SELECT item FROM List2) 

-- alternative 1
EXISTS (SELECT * FROM List2 WHERE List2.item = A)
OR
EXISTS (SELECT * FROM List2 WHERE List2.item = B) 

-- alternative 2
EXISTS (SELECT * FROM List2 WHERE List2.item IN (A,B))


If the values are not already in tables, then a way to write this would be using VALUES clause but this has not been implmented in mySQL:

EXISTS ( SELECT * 
         FROM (VALUES (A), (B)) AS List1 (item)
           JOIN 
              (VALUES (X), (Y), ... (W)) AS List2 (item) 
           ON List1.item = List2.item )


In MySQL, you'll have to rewrite the VALUES with rather long subqueries, using UNION

EXISTS ( SELECT * 
         FROM (SELECT A AS item UNION ALL
               SELECT B
              ) AS List1 
           JOIN 
              (SELECT X AS item UNION ALL
               SELECT Y         UNION ALL
               ... 
               SELECT W
              ) AS List2 
           ON List1.item = List2.item )

Code Snippets

A IN(X, Y, ..., W) OR B IN(X, Y, ..., W)
EXISTS ( SELECT * 
         FROM List1 JOIN List2 ON List1.item = List2.item )
A IN (SELECT item FROM List2) 
OR 
B IN (SELECT item FROM List2) 

-- alternative 1
EXISTS (SELECT * FROM List2 WHERE List2.item = A)
OR
EXISTS (SELECT * FROM List2 WHERE List2.item = B) 

-- alternative 2
EXISTS (SELECT * FROM List2 WHERE List2.item IN (A,B))
EXISTS ( SELECT * 
         FROM (VALUES (A), (B)) AS List1 (item)
           JOIN 
              (VALUES (X), (Y), ... (W)) AS List2 (item) 
           ON List1.item = List2.item )
EXISTS ( SELECT * 
         FROM (SELECT A AS item UNION ALL
               SELECT B
              ) AS List1 
           JOIN 
              (SELECT X AS item UNION ALL
               SELECT Y         UNION ALL
               ... 
               SELECT W
              ) AS List2 
           ON List1.item = List2.item )

Context

StackExchange Database Administrators Q#148986, answer score: 5

Revisions (0)

No revisions yet.