I am reading tick value of the record with largest id. What is the difference between following queries that causes to slow execution?
Slow Query:
SELECT tick
FROM eventlog
WHERE id IN (SELECT max(id) FROM eventlog)
Quick Query:
SELECT max(id) INTO @id
FROM eventlog;
SELECT tick
FROM eventlog
WHERE id = @id;
Schema
CREATE TABLE eventlog (
id INT (11) NOT NULL AUTO_INCREMENT,
tick INT NOT NULL,
eventType_id INT NOT NULL,
compType INT (10) UNSIGNED NOT NULL,
compID INT (10) UNSIGNED NOT NULL,
value_double DOUBLE NOT NULL,
value_int INT (10),
hierarchy_id VARCHAR (255) NOT NULL,
PRIMARY KEY (id),
INDEX htet (
hierarchy_id,
tick,
eventType_id
)
)
Because the
inquery doesn’t use index, the mysql will scan all the records to find the row.From http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html
There’s no
INAnd
there’s no
INeither.As @tombom mentioned,
foo IN ('bar', 'bla')is short forfoo = 'bar' OR foo = 'bla', however, I believe they’re different. So I make a test on a table with enough data records, and find out the following:Then I try the
INquery with static sequences, it works as @tombom mentioned:I don’t know whether the mysql would convert the
INquery intoORsone when possible(for instance, the sequences is known before query), and I didn’t find related documents, but theexplainshows that it did scan the table in this situation.