【问题标题】:mysql where not in to left outer joinmysql where not in to left outer join
【发布时间】:2015-05-29 19:07:21
【问题描述】:

我有以下查询,并希望将其转换为使用左外连接而不是 not in,以查看它是否会以这种方式运行得更快。目前在我们的数据库上运行此查询大约需要 40 秒。我对使用外连接来自己转换这种类型的东西还不够熟悉。

select
    c.contact_id as contact_id,
    c.orgid as organization_id,
    c.first_name as first_name,
    c.last_name as last_name,
    a.address_state as state
from cnx_contact as c
inner join cnx_address as a on c.home_address_uid = a.address_uid
where a.address_state = 'OH'
and (c.orgid = 45 or c.orgid = 55)
and c.contact_id NOT IN (
    select pc.contact_id
    from cnx_contact as c
    inner join cnx_address as a on c.home_address_uid = a.address_uid
    inner join cnx_contact_group_participant as gp on c.contact_id = gp.contact_id
    inner join cnx_contact_participant_role as cr on gp.participant_role_uid = cr.participant_role_uid
    inner join cnx_contact_group as cg on gp.group_uid = cg.group_uid
    inner join cnx_contact_group_participant as pgp on cg.primary_participant_uid = pgp.participant_uid
    inner join cnx_contact as pc on pgp.contact_id = pc.contact_id
    where (c.orgid = 45 or c.orgid = 55)
    and   cr.name = 'Applicant'
);

【问题讨论】:

  • 如果我错了,有人纠正我,但我不认为 NOT INLEFT JOIN 做同样的事情......
  • 它们不做同样的事情,但在很多情况下,您可以使用外连接作为执行此类过滤的更有效方式。它可能不适用于此查询,但不确定。
  • 好吧,我认为您必须进行左连接,并且只选择连接列为空的位置(意味着没有关系),但我不确定是否有任何关系更快。
  • 这可能与您有关:stackoverflow.com/questions/6777910/…

标签: mysql join notin


【解决方案1】:
select
    c.columns
from cnx_contact as c
inner join cnx_address as a on c.home_address_uid = a.address_uid

LEFT JOIN 
(Subquery goes here) x
ON x.contact _id = c.contact_id
where a.participant_state = 'OH'
and c.orgid IN(45,55)
and x.contact_id IS NULL;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-04
    • 2011-01-02
    • 2021-11-29
    • 1970-01-01
    • 2016-05-27
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多