如果有IN子句,如何使用UNION ALL?

时间:2015-12-30 12:39:13

标签: mysql union-all

我有这样的查询:

select p.title
from Posts p
where p.id in (select id from Votes where timestamp between $x and $y);

现在想要使用此表而不是Posts

select title from Posts1
union all
select title from Posts2

如何在第一个查询中编写此^而不是Posts

4 个答案:

答案 0 :(得分:2)

尝试以下查询,希望它会表现更好 -

SELECT p.title FROM Posts1 p JOIN votes v ON p.id=v.id
WHERE v.timestamp BETWEEN $X AND $Y
UNION ALL 
SELECT p.title FROM Posts2 p JOIN votes v ON p.id=v.id
WHERE v.timestamp BETWEEN $X AND $Y;

答案 1 :(得分:1)

您可以嵌套查询

select title from
(select id,title from Posts1 union all select id,title from Posts2) from t1
where t1.id in (select id from Votes where timestamp between $x and $y);

或将where查询添加到两个选择查询:

select title from Posts1 where Posts1.id in (select id from Votes where timestamp between $x and $y)
union all
select title from Posts2 where Posts2.id in (select id from Votes where timestamp between $x and $y);

答案 2 :(得分:1)

你可以试试这个:

select title from (select id,title from Posts1 union all select id,title from Posts2) p
where p.id in (select id from Votes where timestamp between $x and $y);

或者你可以像

那样做
select title from Posts1 p1 where p1.id in (select id from Votes where timestamp between $x and $y)
union all
select title from Posts2 p2 where p2.id in (select id from Votes where timestamp between $x and $y);

答案 3 :(得分:1)

您可以在查询中使用join。这将解决问题

select Posts.title from Posts inner join Votes on Posts.id=Votes.id
where votes.timestamp between $x and $y