简体   繁体   English

更改SQL查询以显式控制执行顺序

[英]Change SQL query to explicitly control the execution sequence

Say I have a query: 说我有一个查询:

SELECT * FROM tb1
WHERE col1 = 1
 AND col2 = 2

Assume col1 is more selective and the engine will normally execute col1 = 1 firstly to gain better performance. 假设col1更具选择性,引擎通常会首先执行col1 = 1以获得更好的性能。 If the conditions become more complicated, the engine may easy to make the wrong decision. 如果情况变得更加复杂,则发动机可能容易做出错误的决定。 So I want to control the execution sequence explicitly, how can I make it? 所以我想显式地控制执行顺序,我该如何做呢?

I guess one way may work. 我想一种方法可能有效。 Firstly query 首先查询

SELECT * FROM tb1
WHERE col1 = 1

select the result into a temp table, then filter by col2 = 2 , but as the conditions grow more and more, of course it's impossible to create so many temp table. 将结果选择到临时表中,然后按col2 = 2进行过滤,但是随着条件的增长,当然不可能创建这么多临时表。 Any ideas? 有任何想法吗?

Update 1 更新1

People say the optimizer always makes the right decision on which filter should be executed firstly to gain better performance, but I still suspect it can work 100% of the time as the query grows larger and more complicated. 人们说优化器总是对应该首先执行哪个过滤器以获得更好的性能做出正确的决定,但是我仍然怀疑,随着查询变得越来越大和越来越复杂,它可以100%地工作。

Another question, can I change the execution order by subquery or CTE? 另一个问题,我可以通过子查询或CTE更改执行顺序吗? like: 喜欢:

SELECT * FROM 
(
   SELECT * FROM tb1 WHERE col1 = 1
)t
WHERE col2 = 2

Usually SQL Optimizer can find the better plan, but if you want to fix it, there are options... 通常,SQL Optimizer可以找到更好的计划,但是如果您要对其进行修复,则可以选择...

You may create a test data set for which SQL engine chooses correct (desired) plan, then you can extract the query plan to XML string (see SET SHOWPLAN_XML ON ) and finally use WITH PLAN option (query hint) to fix the plan. 您可以创建一个测试数据集,SQL引擎为其选择正确的(所需)计划,然后可以将查询计划提取到XML字符串(请参阅SET SHOWPLAN_XML ON),最后使用WITH PLAN选项(查询提示)来修复该计划。

Keep in mind that query will fail if you change the schema in the future without updating the plan. 请记住,如果将来在不更新计划的情况下更改架构,查询将失败。

To achieve this you should use query hints. 为此,您应该使用查询提示。

  1. You can use USE PLAN query hint. 您可以使用USE PLAN查询提示。
  2. Use with(index(index_name)) created for specific row order. with(index(index_name))为特定行顺序创建的with(index(index_name))使用。

For the first point you have to get XML plan by first executing your query in which you are getting your desired execution order. 首先,您必须通过首先执行查询来获得XML计划,在查询中您将获得所需的执行顺序。 And for second one, just create index on those columns in which you have arranged column in desired order. 对于第二个,只需在按所需顺序排列了列的那些列上创建索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM