Home > Database > Mysql Tutorial > Analyze the efficiency of or and in in mysql with examples

Analyze the efficiency of or and in in mysql with examples

藏色散人
Release: 2021-09-25 17:13:07
forward
2358 people have browsed it

Analyze the efficiency of or and in in mysql with examples

The efficiency of or and in in mysql

Preface

I encountered a website stuck problem today. After a few minutes, it Okay, I found a sql in a timing script, and the execution efficiency is very slow. The DBA suggested changing or to in, and the efficiency increased hundreds of times.

Scenario description

1. Two Table association query
2.The data volume of table1 is close to 1 million
3.The data volume of table2 is close to 9 million
4.The title field in the query condition is not indexed
5.Original query statement

SELECT a.id as id FROM `table1`as a left join table2 as b on a.id=b.id WHERE b.title="衣服" or b.title="裤子" or b.title="帽子" limit 0,100
Copy after login

6. Query statement after transformation

SELECT a.id as id FROM `table1`as a left join table2 as b on a.id=b.id WHERE b.title IN ("衣服","裤子","帽子") limit 0,100
Copy after login

Efficiency after transformation

The original SQL execution time is 5s, after the change it only takes 0.01s

Reason

After checking the information, when the amount of data exceeds one million and the conditions are not indexed, the query efficiency of or is far lower than that of in. The efficiency of or is O(n), while the efficiency of in is O (logn), when n is larger, the efficiency difference becomes more obvious.

Recommended learning: "mysql video tutorial"

The above is the detailed content of Analyze the efficiency of or and in in mysql with examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template