简体   繁体   中英

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 ...

If I follow you correct, you can use exists :

select t.*
from trans t
where exists (
    select 1
    from alerts a
    where 
        <something>
        and t.id = a.id
        and t.web = a.web
        and t.date between t.first_date and t.last_date
)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM