4

我正在尝试优化查询,试图避免重复使用“ COMPLEX QUERY ”指示的查询,该查询使用了 2 次,并且两者都具有相同的结果。

原始查询

SELECT news.* 
FROM   news 
   INNER JOIN((SELECT myposter 
               FROM   (SELECT **COMPLEX QUERY**)) 
              UNION 
              (SELECT myposter 
               FROM   `profiles_old` prof2 
               WHERE  prof2.profile_id NOT IN (SELECT **COMPLEX QUERY**))) r 
           ON news.profile = r.p 

我想知道这样的事情是否可能:

SELECT news.* 
FROM   (SELECT **COMPLEX QUERY**) complexQuery, 
   news 
   INNER JOIN ((SELECT myposter 
                FROM   complexquery) 
               UNION 
               (SELECT myposter 
                FROM   `profiles_old` prof2 
                WHERE  prof2. profile NOT IN (SELECT myposter 
                                              FROM complexQuery))) r 
           ON news. profile = r.p 

Mysql 会对该类型的查询进行某种缓存吗?

4

2 回答 2

5

The direct answer to your question is "no". MySQL does not support what you want. What you really want is the with statement. Great statement! If you want it, use a different database. Alas.

I do think you can do this, although the approach is quite different from what you are doing.

The logic is to take all values of myposter from the complex query and to take all values of myposter from profiles_old where the corresponding profile_id is not in the complex query.

You can do this with union all and aggregation. Just focusing on the inner subquery:

select (case when max(which = 'cq') = 1 then myposter
             when max(which = 'po') = 1 and max(which = 'cq') = 0 then id2
       ) as myposter
from (select myposter, myposter as id2, 'cq' as which
      from (select **complex query**) cq
      union all
      select profile_id, myposter, 'po' as which
      from profiles_old
     ) t
group by myposter;

The rest is just incorporating this into your overall query.

于 2013-11-07T02:26:48.647 回答
0

我已经完成了要求,以不同的方法给出了建议:

/* 创建临时表(优先使用内存存储引擎,虽然它不是强制性的):*/

MYSQL> 创建临时表 tmp_intermediate_table engine=memory select COMPLEX QUERY ;

然后,在当前用户会话中运行的查询中引用 tmp_intermediate_table 表。

于 2014-05-12T09:40:41.390 回答