Ok, here we go... I have used the following test program to make two tables (similar to the example we have been discussing):
Code:
<?php
// Initialize database connection
$con = ...
// Create tables
$sql = "CREATE TABLE single (
col2 INTEGER,
col3 INTEGER,
rowid INTEGER,
INDEX (col2),
INDEX (col3)
) ENGINE=MyISAM";
mysql_query($sql, $con);
$sql = "CREATE TABLE multiple (
col1 INTEGER,
col2 INTEGER,
col3 INTEGER,
rowid INTEGER,
INDEX (col1, col2),
INDEX (col1, col3)
) ENGINE=MyISAM";
mysql_query($sql, $con);
/*
* Table single will have 100,001 rows
* col2 is a random number between 1 and 100
* col3 is a random number between 1 and 20
* Table multiple is a (double) copy of single,
* with col1 of 1 and 2, respectively
*/
$seed = 100;
srand($seed);
for ($i = 0; $i <= 100000; $i++) {
$col2 = rand(1, 100);
$col3 = rand(1, 19); // Edit: should have been 20, but 19 used anyway
$sql = "INSERT INTO single
(col2, col3, rowid)
VALUES
($col2, $col3, $i)";
mysql_query($sql, $con);
$sql = "INSERT INTO multiple
(col1, col2, col3, rowid)
VALUES
(1, $col2, $col3, $i),
(2, $col2, $col3, $i)";
mysql_query($sql, $con);
}
?>
Now, the following statements each return (the same) 59 rows
Code:
SELECT rowid FROM single WHERE col2=71 AND col3=5;
SELECT rowid FROM multiple WHERE col1=1 AND col2=71 AND col3=5;
I attach a screenshot of the EXPLAIN for both statements.
I see that the first query uses only key. This is col2, which makes sense as that returns the smallest number of rows. However, the EXPLAIN output says 1252 rows, while "SELECT rowid FROM single WHERE col2=71" only returns 1009 rows. Also, I thought for the subquery (col3=5) some kind of index merging would happen, but that doesn't seem to be the case. So I guess, MySQL is going through all 1252 (or 1009) rows.
The second query does use index merging but I am not sure how to further interpret the EXPLAIN output. More specificially, how to read "possible_keys: col1,col1_2"?
Any help would be much appreciated.
Bookmarks