In mysql is "WHERE a = 2 AND b = 'Wiliam'" the same as "WHERE b = 'Wiliam' AND a = 2"?
In mysql, does the order of the WHERE clauses affect the t开发者_C百科ime that it takes the server to process the query?
I know that the queries are compiled and optimized, but I don't know if that optimization changes the order of the WHERE clauses so in a hypothetic case it will take less time to process a query that first selects the results with an integer than if it starts with a string index for example.
WHERE a = 2 AND b = 'Wiliam'
- 1: Search in 200 items and find 20 results with value a = 2
- 2: Search in 20 items and find 1 result with b = Wiliam
That
WHERE b = 'Wiliam' AND a = 2
- 1: Search in 200 items and find 20 results with value b = Wiliam
- 2: Search in 20 items and find 1 result with a = 2
Will it be faster if we start searching a integer indexed column? Does mysql know which clause has a worse index to do the second search?
Thanks.
The optimizer can and often will change the order of the evaluation of predicates to better take advantage of the indexes. MySQL keeps statistics on each index and it will use those to choose which index is likely to be fastest. There are no easy rules about which index will be chosen: it is free to choose different indexes depending on the data in the database and the values you are looking for.
In the case where there are no indexes it can make a difference, but it is rarely worth worrying about:
SELECT * FROM table1
WHERE a = 2 AND b = 'Wiliam';
2.9 seconds
SELECT * FROM table1
WHERE b = 'Wiliam' AND a = 2;
2.6 seconds
Test data:
CREATE TABLE filler (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT
) ENGINE=Memory;
DELIMITER $$
CREATE PROCEDURE prc_filler(cnt INT)
BEGIN
DECLARE _cnt INT;
SET _cnt = 1;
WHILE _cnt <= cnt DO
INSERT
INTO filler
SELECT _cnt;
SET _cnt = _cnt + 1;
END WHILE;
END
$$
DELIMITER ;
CALL prc_filler(1000000);
INSERT INTO table1 (a, b)
SELECT id, 'Wiliam' FROM filler;
No, the order of clauses does not matter. In either case, the server will determine the best index to use, regardless of the order. Each index has statistics that MySQL will use to determine which one is more "selective" (that is, which one will require the least number of I/Os to process) and choose that.
精彩评论