2012-06-11 103 views
0

我想要的是一個事件的參與者(人員,作爲參與者的角色),以及與參與者相同公司的人員,但其角色是經理。查詢更有效

一個人的角色是存儲在person_role_membership中的商店,但是一個人的公司存儲在People中。我製作了以下查詢,我認爲這項工作非常好。請忽略額外的連接和信息。我把所有的參與者都提取出來,然後和所有的經理們進行聯合,爲此我再次提取所有參與者。現在麻煩的是整個查詢,因爲一個小子集需要9秒。有沒有辦法讓它更快?

select distinct * 
from 
(
SELECT 
p.id as p_id, p.first_name as p_first_name, p.last_name as p_last_name,p_r.name as p_role, 
p.job_title as p_job_title, 
p_d.email as p_email, p_d.phone_1 as p_phone, p_d.phone_ext_1 as p_ext, 
c.name as p_company, p_c.name as p_parent_company 

FROM person_role_memberships as prm 

left join people as p on prm.person_id = p.id and prm.person_role_id between 32 and 35 
left join person_roles as p_r on p_r.id = prm.person_role_id 
left join person_details as p_d on p.id = p_d.person_id and p_d.type = 'BusinessDetail' 
left join companies as c on c.id = p.company_id 
left join companies as p_c on p_c.id = p.parent_company_id 

where 
p.id is not null 

) as parts 
union (

select p.id, p.first_name,p.last_name,prm.person_role_id, p.job_title, 'cp email', 'phone','ext',c.name, d.name 

from people as p -- All those people 

left join person_role_memberships as prm on prm.person_id = p.id -- whose roles are like this 
left join companies as c on p.company_id = c.id 
left join companies as d on c.parent_id = d.id 
-- and whose companies are like those people whose roles are like this 

where company_id = any 
(
select company_id from people as p 
left join person_role_memberships as prm on prm.person_id = p.id 
where prm.person_role_id between 32 and 35-- and other conditions; 
) 

and (person_role_id = 14 or person_role_id = 15)) 

回答

0

我的猜測是,您的查詢「任何」部分正在放緩下來。通過外觀上來看,我認爲你甚至都不需要它,因爲你可以在person_role_memberships直接過濾:

select p.id, p.first_name,p.last_name,prm.person_role_id, p.job_title, 'cp email', 'phone','ext',c.name, d.name 

from people as p -- All those people 
    left join person_role_memberships as prm on prm.person_id = p.id -- whose roles are like this 
    left join companies as c on p.company_id = c.id 
    left join companies as d on c.parent_id = d.id 

-- and whose companies are like those people whose roles are like this 
where prm.person_role_id between 32 and 35 -- and other conditions; 
    and (person_role_id = 14 or person_role_id = 15)) 

的「any'語句導致數據庫在整個people表查找每個記錄。