I have a table named user
with 20 million rows in total. The table info is id, name, ctime
and only id
is indexed.
I'd like to query select min(id) from user where citme > 1521882950
.
The result time is around 7-10 seconds.
When I query with select min(id) from user
, the result time is around 10ms. I think the reason is because id
is indexed by mysql. So the query is fast.
Since indexing ctime
is not so meaningful for the table, I am thinking if there is another way to query in less than 1 second without indexing the ctime
column?
From mysql dev page, I found this explaining about indexing , I don't know how to apply the greater condition.
SELECT MIN(key_part2),MAX(key_part2)
FROM tbl_name WHERE key_part1=10;
For
SELECT MIN(key_part2),MAX(key_part2)
FROM tbl_name WHERE key_part1=10;
you need
INDEX(key_part1, key_part2)
What you have is
SELECT MIN(key_part2) -- id
FROM tbl_name WHERE key_part1=10; -- ctime
which needs
INDEX(ctime, id)
However, InnoDB's secondary indexes automatically include the PK, so saying merely
INDEX(ctime)
happens to have the same effect. (I prefer to say INDEX(ctime, id)
as a clue to the reader that I need that pair.)
"Since indexing ctime is not so meaningful for the table" -- Well, it was meaningful for that one query! So, index it.
Without the index, the entire table will be read to process the query.
With the index, only one row in the INDEX
will be read to get the result.
That's about as extreme as it gets (having vs not having an index).
Meanwhile,
select min(id) from user
uses the PRIMARY KEY
and reads only one row to get the answer.
"I am thinking if there is another way to query in less than 1 second without indexing the ctime column?" Why does it matter? Simply add the index and be done with the issue.
I asked someone around. It seems there is no better way to query a column without index within seconds. For my case, the best way for mysql to query fast is indexing the column ctime
.
If there is a better answer, please update.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.