簡體   English   中英

MYSQL 從另一個查詢導入的多個“或”條件

[英]MYSQL multiple 'OR' conditions imported from another query

是否可以創建具有多個 OR 條件的查詢,例如:

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 子句中的“或行”:

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

所以這最后一個查詢會給我一個像這樣的表:

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

所以我在第一個查詢中想要的結果就像從前一個表的每行執行一個查詢,比如:

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

如果我跟你說得對,你可以使用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
)

它看起來像 JOIN 問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM