【问题标题】:Making the query for more efficient使查询更高效
【发布时间】:2012-06-11 12:10:34
【问题描述】:

我想要的是一个事件的参与者(具有参与者角色的人),以及与参与者来自同一公司但角色是经理的人。

Person 的角色存储在 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))

【问题讨论】:

    标签: mysql sql join nested-queries


    【解决方案1】:

    我的猜测是您查询的“任何”部分会减慢速度。从外观上看,我认为您甚至不需要它,因为您可以直接过滤 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 表中的每条记录。

    【讨论】:

      猜你喜欢
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多