Query optimization in this case
I am asking this by curiosity. This could be the most stupid question or basic question. Forgive me if it is..
Suppose I have a isThatA table contains id, class, school_id having 1000 records.
There are 3 schools and 12 classes.
Which of these 2 queries would be faster(if there is a difference)
Query 1: SELECT * FROM isThatA WHERE school=2 and class=5;
Query 2: SELECT开发者_运维百科 * FROM isThatA WHERE class=5 and school=2;
Note: I just changed the places of the 2 conditions in WHERE
Also probable number of records for condition WHERE school=2 is 333
And probable number of records for condition WHERE class=5 is 80.
There's no difference there. Use EXPLAIN SELECT ...
to discover what approach does MySQL choose to optimize and run your queries. That will answer your question.
The first one will be faster if it is a Tuesday, and the second one will be faster any other day of the week. The performance reverses if a unicron comes out to play.
In all seriousness - both queries build the same query expression tree since the where-and clauses are commutative so there can be no possible difference in performance
Both queryies gives the exact same performance, as the database determines how to do the query most efficiently before running it.
To get good performance in a query you should make sure that there is an index that the database can use to filter out the records. In this case you should create an index containing school
and class
.
Also, don't use select *
in a query (other than for testing), you should always specify which fields you want to return from the query. That way you don't return data that you don't use, you know that the fields are returned in the order that you want, and adding more fields to the table doesn't make the query return more unused data.
If you only need one ore a few fields from the table, add those as output fields (or "included columns") to the index. That way the database can get the result without even touching the table itself.
精彩评论