如何加入两个查询,哪一个由两部分组成?

时间:2015-11-17 16:04:18

标签: mysql join

我有两个这样的查询:

查询1:

Maintain

结果表的名称为SELECT id, title col2, content col3 FROM Posts1 WHERE title = :q UNION ALL SELECT id, subject col2, description col3 FROM Posts2 WHERE Match (subject) AGAINST (:q)

现在我想加入Posts3 Posts3Votes

QUERY2:

ON Posts3.id = Votes.Posts_id

那么,如何联合上述两个查询呢?

示例:

SELECT id, sum(vote) From Votes

假设这是// Posts1 // Posts2 +----+-------+---------------+ +----+---------+------------------+ | id | title | content | | id | subject | description | +----+-------+---------------+ +----+---------+------------------+ UNION ALL的结果(Posts1):

Posts2

我也有// Posts3 +----+-------+---------------+ | id | col2 | col3 | +----+-------+---------------+ 这样的表:

Votes

现在,我想知道,我怎么能// Votes +----+------+ | id | vote | +----+------+

1 个答案:

答案 0 :(得分:1)

将查询用作派生表/内联视图...别名并将它们视为表。所以我们将query1别名为posts3,将别名查询2别名为V

Select * 
from 
(SELECT id, title col2, content col3 
 FROM Posts1 
 WHERE title = :q
 UNION ALL
 SELECT id, subject col2, description col3 
 FROM Posts2 
 WHERE Match (subject) AGAINST (:q)) Posts3
INNER JOIN (Select ID, Sum(Vote) from votes) V
 on V.ID = Posts3.ID

可能有一种方法可以在没有两个单独查询的情况下组合结果,从而获得更好的性能,但我相信这可以回答基本问题。