Search code examples
mysqlsqlsubquerywhere-clause

MYSQL multiple 'OR' conditions imported from another query


Is it possible to create a query that has multiple OR conditions like:

SELECT
  *
FROM
  trans 
WHERE 
  (web = 'web1' AND date BETWEEN ('first_date1' AND 'last_date1') OR 
  (web = 'web2' AND date BETWEEN ('first_date2' AND 'last_date2') OR 
  (web = 'web3' AND date BETWEEN ('first_date3' AND 'last_date3') OR
  (web = 'web4' AND date BETWEEN ('first_date4' AND 'last_date4') OR
  ...
  ...
WHERE 
  something1

Where this "OR rows" in the WHERE clause I can get them from another query from another table:

SELECT id, web, first_date, last_date
FROM
  alerts 
WHERE 
  something2

so this last query will give me a table like:

+-----+------+-------------+------------+
| ID  | web  | first_date  | last_date  |
+-----+------+-------------+------------+
| 23  | web1 | first_date1 | last_date1 |
+-----+------+-------------+------------+
| 2   | web2 | first_date2 | last_date2 |
+-----+------+-------------+------------+
| 33  | web3 | first_date3 | last_date3 |
+-----+------+-------------+------------+
| 5   | web4 | first_date4 | last_date4 |
+-----+------+-------------+------------+
| ... | ...  | ...         | ...        |
+-----+------+-------------+------------+

so the result I want in the first query will be like executing one query per row form the previous table, somthing like:

SELECT * FROM trans 
WHERE web = 'web1' AND date BETWEEN ('first_date1' AND 'last_date1')

SELECT * FROM trans 
WHERE web = 'web2' AND date BETWEEN ('first_date2' AND 'last_date2')

and so on ...

Solution

  • It looks as JOIN problem:

    SELECT
      trans.*, a.alert_id
    FROM
      trans t
    JOIN 
     (
       SELECT id as alert_id, web, first_date, last_date 
       FROM  alerts 
       WHERE 
       something2
     ) as  ON (
       a.web = t.web1 AND 
       t.date BETWEEN (a.first_date1 AND a.last_date1)
     )
    WHERE 
      something