在MYSQL中优化Union All

时间:2013-12-16 09:06:49

标签: mysql sql performance select query-optimization

我的查询执行时间超过10秒。请提供一些建议来即兴发出以下查询!

CREATE TABLE uem_map_user_event (
    id INT(11) , uem_user_id INt(10),uem_event_type_id INT(11),
    uem_entry_date DATETIME ,INDEX urt_user_id (uem_user_id) );

   CREATE TABLE evy_mst_event_type (id INT(11) , evy_description VARCHAR(45),
    evy_event_family_id INT(11),PRIMARY KEY (id) );

CREATE TABLE uft_map_user_clnt (
    id INT(11) ,uft_user_id INT(11) ,uft_clnt_id INT(11) ,uft_eff_frmdt DATETIME ,
    uft_eff_todt DATETIME ,uft_add_userid INT(11) ,uft_mod_userid INT(11) );

select * from (
select u.id as id,evy.description as 'Work Description',count(*) as Pending
from  user_event u
join event_type evy on evy.id = u.event_type_id
join (select fun.eventtypeid ,fun.client_id  ,uft.user_id  
from  vw_fund_queue fun 
join uft_clnt uft on uft.uft_clnt_id = fun.client_id  
) evt on evy.id = evt.eventtypeid
and u.user_id = evt.user_id 
where evy.id = 1601 and u.user_id  = 10061

union all

select u.id as id,evy.description as 'Work Description',count(*) as Pending
from user_event u
join event_type evy on evy.id = u.event_type_id
join (select fun.eventtypeid ,fun.client_id  ,uft.user_id 
from  vw_fund_confirm fun 
join uft_clnt uft on uft.uft_clnt_id = fun.client_id  
) evt on evy.id = evt.eventtypeid
and u.user_id = evt.user_id 
where evy.id = 1201 and u.user_id  = 10061

union all

select u.id as id,evy.description as 'Work Description',count(*) as Pending
 from  user_event u 
join event_type evy on evy.id = u.event_type_id
join (select fun.eventtypeid ,fun.client_id  ,uft.user_id 
from  vw_fund_approve fun 
join uft_user_clnt uft on uft.clnt_id = fun.client_id  
) evt on evy.id = evt.eventtypeid
and uem.user_id = evt.user_id 
where evy.id = 1202 and u.user_id  = 10061 ) a where a.pending!=0

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT u.id AS id,evy.description AS 'Work Description', COUNT(1) AS Pending
FROM  user_event u
JOIN event_type evy ON evy.id = u.event_type_id
JOIN (SELECT fun.eventtypeid ,fun.client_id  ,uft.user_id  
      FROM  vw_fund_queue fun 
      JOIN uft_clnt uft ON uft.uft_clnt_id = fun.client_id  
      WHERE fun.eventtypeid = 1601 AND uft.user_id = 10061 
     UNION ALL 
      SELECT fun.eventtypeid ,fun.client_id  ,uft.user_id 
      FROM  vw_fund_confirm fun 
      JOIN uft_clnt uft ON uft.uft_clnt_id = fun.client_id  
      WHERE fun.eventtypeid = 1201 AND uft.user_id = 10061
    UNION ALL
     SELECT fun.eventtypeid ,fun.client_id  ,uft.user_id 
     FROM  vw_fund_approve fun 
     JOIN uft_user_clnt uft ON uft.clnt_id = fun.client_id  
     WHERE fun.eventtypeid = 1202 AND uft.user_id = 10061
    ) evt ON evy.id = evt.eventtypeid AND u.user_id = evt.user_id 
GROUP BY evy.id HAVING pending != 0