0

I have similar situation like question below.

Mysql speed up max() group by

SELECT MAX(id) id, cid FROM table GROUP BY cid

To optimize above query (shown in the question), creating index(cid, id) does the trick.

However, when I add a column that is not indexed to SELECT, query speed drastically slows down.

For example,

SELECT MAX(id) id, cid, newcolumn FROM table GROUP BY cid

If I create index(cid, id, newcolumn), query time comes back to minimal. It seems I should index all the columns I select while using GROUP BY.

Is there any way other than indexing all the columns to be select?

4

1 回答 1

1

当查询中使用的所有列都是索引的一部分(然后称为覆盖索引)时,SQLite 可以从索引中获取所有值,而无需访问表本身。

添加未编入索引的列时,必须在索引和表中查找每条记录。此外,表中记录的顺序不可能与索引中的顺序相同,因此表的页面不是按顺序读取的,而是被多次读取的,这意味着缓存也不起作用。

这些newcolumn值必须从表或索引中读取;没有其他机制来存储数据。

tl;博士:没有

于 2013-07-05T19:25:52.843 回答