![](/img/trans.png)
[英]Mysql Query for inserting from one table to another on Multiple conditions and columns
[英]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.