mysql where not in to left outer join
Posted
技术标签:
【中文标题】mysql 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 IN
和 LEFT JOIN
做同样的事情......
它们不做同样的事情,但在很多情况下,您可以使用外连接作为执行此类过滤的更有效方式。它可能不适用于此查询,但不确定。
好吧,我认为您必须进行左连接,并且只选择连接列为空的位置(意味着没有关系),但我不确定是否有任何关系更快。
这可能与您有关:***.com/questions/6777910/…
【参考方案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;
【讨论】:
以上是关于mysql where not in to left outer join的主要内容,如果未能解决你的问题,请参考以下文章
MySQL 子查询优化 - where not in(子查询)
MySQL:在 WHERE 子句中带有 NOT IN 的从属子查询非常慢
MySQL SELECT WHERE IN LIST 和 NOT IN LIST 在同一 SQL 中
努力优化 Rails WHERE NOT IN 在 Rails 中的查询