在表扫描之前进行SQL优化JOIN?

时间:2019-01-18 19:26:32

标签: sql sql-server

我有一个类似的SQL查询

SELECT columnName 
FROM 
     (SELECT columnName, someColumnWithXml 
      FROM _Table1
      INNER JOIN _Activity ON _Activity.oid = _Table1.columnName
      INNER JOIN _ActivityType ON _Activity.activityType = _ActivityType.oid
      --_ActivityType.forType is a string
      WHERE _ActivityType.forType = '_Disclosure'
        AND _Activity.emailRecipients IS NOT NULL) subquery
WHERE subquery.someColumnWithXml LIKE '%'+'9D62EE8855797448A7C689A09D193042'+'%'

_Table1中有1500万行,WHERE subquery.someColumnWithXml LIKE '%'+'9D62EE8855797448A7C689A09D193042'+'%'产生了一个执行计划,该计划对所有1500万行执行全表扫描。子查询仅产生数十万行,而这些实际上是需要在其上运行LIKE的所有行。是否有一种方法可以通过仅对子查询的结果运行LIKE而不是对15,000,000行运行带有LIKE的TABLE SCAN来提高效率? someColumnWithXML列未编制索引。

2 个答案:

答案 0 :(得分:0)

您可以直接在子查询中过滤,避免扫描无用的行

      SELECT columnName, someColumnWithXml 
      FROM _Table1
      INNER JOIN _Activity on _Activity.oid = _Table1.columnName
      INNER JOIN _ActivityType on _Activity.activityType = _ActivityType.oid
      --_ActivityType.forType is a string
      WHERE _ActivityType.forType = '_Disclosure'
      AND _Activity.emailRecipients IS NOT NULL
      someColumnWithXml LIKE '%'+'9D62EE8855797448A7C689A09D193042'+'%'

答案 1 :(得分:0)

对于此查询:

SELECT columnName, someColumnWithXml
FROM _Table1 t1 INNER JOIN
     _Activity a
     ON a.oid = t1.columnName INNER JOIN
     _ActivityType at
     ON a.activityType = at.oid --_ActivityType.forType is a string
WHERE at.forType = '_Disclosure' AND
      a.emailRecipients IS NOT NULL AND
      t1.someColumnWithXml LIKE '%'+'9D62EE8855797448A7C689A09D193042'+'%';

您在优化此查询方面遇到了挑战。我不知道过滤条件是否特别严格。如果是,则在以下位置进行索引:

  • _ActivityType(forType, oid)
  • _Activity(activityType, emailRecipients, oid)
  • _Table1(columnName)

如果这些方法没有帮助,则可以在XML列上建立索引。 Perhaps an XML index would work.这样的索引对于通用的LIKE并没有真正的帮助,但是如果您解析XML,则可能不需要。