简体   繁体   English

为什么where子句中的无用语句会减慢sql查询速度?

[英]why useless statements in where clause slow down the sql query speed?

I have two queries below:我有以下两个疑问:

SELECT cl.`cl_boolean`, l.`l_name`
FROM `card_legality` cl
LEFT JOIN `legality` l ON l.`legality_id` = cl.`legality_id`
WHERE cl.`card_id` = 23155


SELECT cl.`cl_boolean`, l.`l_name`
FROM `card_legality` cl
LEFT JOIN `legality` l ON l.`legality_id` = cl.`legality_id`
WHERE cl.`card_id` = 23155 or 1 = 2

(this is not the true case, just show the problem) (这不是真实情况,只是显示问题)

I want to know why the second one is so slow(almost 100 times slower in true case).我想知道为什么第二个这么慢(在真实情况下几乎慢了 100 倍)。

Okay, below is the query(oracle) in my case:好的,下面是我的查询(oracle):

select *
from LA_TESTCASE this_ 
left outer join LA_RULE   rule1_    on this_.ROOTCAUSE_RULE_ID = rule1_.ID 
left outer join LA_TEST   test2_    on this_.TEST_ID = test2_.ID 
left outer join LA_SUITE  suite3_   on test2_.SUITE_ID = suite3_.ID 
left outer join LA_RUN    run4_     on suite3_.RUN_ID = run4_.ID
where (run4_.NAME = 'RRP_XO-245'/* or 1 = 2*/)
order by this_.ID desc;

It's almost the same as the sample case.这与示例案例几乎相同。

"It's almost the same as the sample case.". “这和样本案例几乎一样。”。 actually it's nothing like it.实际上,它一点也不像。

in the first case, you were filtering on the left table of a left join.在第一种情况下,您在左联接的左表上进行过滤。 in the second, you are filtering on the right (outer joined table) of the query.在第二个中,您在查询的右侧(外部连接表)进行过滤。

the presence of OR 1=2 in that case will most likely cause a full table scan to resolve it (again, run the explain plans to see this).在这种情况下 OR 1=2的存在很可能会导致全表扫描来解决它(再次运行解释计划以查看此问题)。

but your query makes no sense in that you are outer joining RUN4_ but then filtering on it in the WHERE clause (not the join itself).但是您的查询没有意义,因为您是外部加入 RUN4_ ,然后在 WHERE 子句中对其进行过滤(而不是连接本身)。

run4_.NAME = 'RRP_XO-245'

you should tidy up the logic of the query.你应该整理一下查询的逻辑。

In this case the cause is OR .在这种情况下,原因是OR

In the first query, the engine may use an index on card_id.在第一个查询中,引擎可能会使用 card_id 上的索引。 It uses probably a hash join to join the two tables.它可能使用散列连接来连接两个表。

In the second the existence of OR cause the possibility of existence more rows that may not have card_id=23155.在第二个中, OR的存在导致存在更多可能没有 card_id=23155 的行的可能性。 So, the index is useless: it should scan the entire table.所以,索引是无用的:它应该扫描整个表。

Also, in general or conditions are harder to put in hash joins, so it may be forced to do a NESTED LOOOPS JOIN.此外,一般情况下or条件更难放入散列连接,因此可能会被迫执行嵌套循环连接。

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

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