MySQL查询速度慢,子查询

时间:2014-05-26 19:25:59

标签: mysql performance subquery

我有这个SQL查询:

SELECT `ownExternalContactID`
FROM `sc_users`
WHERE `sc_users`.`id` IN
    ( SELECT `id`
     FROM `sc_users`
     WHERE `ownExternalContactID` IN
         ( SELECT `externalContactID`
          FROM `sc_external_contact_data`
          WHERE `value` IN
              ( SELECT `value`
               FROM `sc_external_contact_data`
               WHERE `externalContactID` IN
                   (SELECT `id`
                    FROM `sc_external_contacts`
                    WHERE `ownerUserID` = "158") ) ) )
  AND `sc_users`.`id` IN
    ( SELECT `ownerUserID`
     FROM `sc_external_contacts`
     WHERE `id` IN
         ( SELECT `externalContactID`
          FROM `sc_external_contact_data`
          WHERE `value` IN
              ( SELECT `value`
               FROM `sc_external_contact_data`
               WHERE `externalContactID` =
                   (SELECT `ownExternalContactID`
                    FROM `sc_users`
                    WHERE `id` = "158") ) ) )
  AND `sc_users`.`id` != "158"

它用于双向地址簿条目匹配,其中它比较表sc_external_contact_data中的散列地址簿条目,然后将其与表sc_external_contactssc_users连接。到目前为止,这么好,这个查询非常快,在我的特定实例中,它返回条目359和1091.

这真的很方便,所以现在我知道相关的外部联系人有ID 359和1091.现在,我想做的是得到他们各自的哈希值,所以我可以稍后将它们发送到客户端进行本地匹配与地址簿。我通过将上层查询嵌入到此中来做到:

SELECT * FROM `sc_external_contact_data` WHERE `externalContactID` IN (/* upper query */)

如果你好奇它的样子,它看起来像这样:

SELECT *
FROM `sc_external_contact_data`
WHERE `externalContactID` IN
    ( SELECT `ownExternalContactID`
     FROM `sc_users`
     WHERE `sc_users`.`id` IN
         ( SELECT `id`
          FROM `sc_users`
          WHERE `ownExternalContactID` IN
              ( SELECT `externalContactID`
               FROM `sc_external_contact_data`
               WHERE `value` IN
                   ( SELECT `value`
                    FROM `sc_external_contact_data`
                    WHERE `externalContactID` IN
                        (SELECT `id`
                         FROM `sc_external_contacts`
                         WHERE `ownerUserID` = "158") ) ) )
       AND `sc_users`.`id` IN
         ( SELECT `ownerUserID`
          FROM `sc_external_contacts`
          WHERE `id` IN
              ( SELECT `externalContactID`
               FROM `sc_external_contact_data`
               WHERE `value` IN
                   ( SELECT `value`
                    FROM `sc_external_contact_data`
                    WHERE `externalContactID` =
                        (SELECT `ownExternalContactID`
                         FROM `sc_users`
                         WHERE `id` = "158") ) ) )
       AND `id` != "158" )

突然,查询变得极其缓慢,只返回两个条目。

但是,如果你运行这样的查询:

SELECT * FROM `sc_external_contact_data` WHERE `externalContactID` IN (359, 1091)

它的突然变化速度应该和它一样快,而不是两次,而是四次。

所以我的问题是:这些嵌入式查询之间究竟有什么区别,为什么存在速度差异?如果第一个查询如此快速地获取这些ID,为什么将它用作子查询会如此禁止这些性能?为什么结果不同?

截至目前,我似乎无法找到任何括号匹配错误。谢谢!

0 个答案:

没有答案