简体   繁体   中英

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).

Okay, below is the query(oracle) in my case:

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).

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_.NAME = 'RRP_XO-245'

you should tidy up the logic of the query.

In this case the cause is OR .

In the first query, the engine may use an index on 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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