【发布时间】:2016-03-09 20:02:18
【问题描述】:
我无法理解以下两个查询。第一个仅获取整个结果集的计数。
第二个获取实际数据,但将结果集限制为 10 行。
- 不知何故,第一个不能使用索引。我尝试使用
USE INDEX (timestamp_index,Fulltext_title,Fulltext_description)无济于事。 - count查询不需要order by,但我只是想看看它是否可以这样使用索引。
- 据我所知,WHERE 子句是相同的,据我所知,这是选择索引的最大因素。
获取计数
SELECT count(*) as total FROM table1
WHERE 1=1
AND type in ('category1','category3','category2')
AND (
MATCH(title) AGAINST (' +"apple"' IN BOOLEAN MODE)
OR
MATCH(description) AGAINST (' +"apple"' IN BOOLEAN MODE)
)
ORDER BY timestamp DESC
;
+-------+
| total |
+-------+
| 798 |
+-------+
1 row in set (3.75 sec)
解释扩展
+----+-------------+----------+------+---------------+------+---------+------+--------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+----------+------+---------------+------+---------+------+--------+----------+-------------+
| 1 | SIMPLE | table1 | ALL | NULL | NULL | NULL | NULL | 669689 | 100.00 | Using where |
+----+-------------+----------+------+---------------+------+---------+------+--------+----------+-------------+
获取实际结果
SELECT id, title,desciption,timestamp FROM table1
WHERE 1=1
AND type in ('category1','category3','category2')
AND (
MATCH(title) AGAINST (' +"apple"' IN BOOLEAN MODE)
OR
MATCH(description) AGAINST (' +"apple"' IN BOOLEAN MODE)
)
ORDER BY timestamp DESC
LIMIT 0, 10 ;
10 行(0.06 秒)
解释扩展
+----+-------------+----------+-------+---------------+------+---------+------+------+------------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+----------+-------+---------------+------+---------+---- --+------+------------+-------------+
| 1 | SIMPLE | table1 index | NULL | timestamp_index | 21 | NULL | 10 | 6696890.00 | Using where |
+----+-------------+----------+-------+---------------+------+---------+------+------+------------+-------------+
【问题讨论】:
-
limit对优化器的影响非常大,我不确定你要问这个问题 - 这两个查询完全不同。 -
这个限制会让它运行得更快。 Count(*) 必须进行全表扫描,尤其是在第一次运行时。它可能会提高后续调用的性能。
-
好的 ... 让我改一下 .. 我怎样才能让第一个查询使用索引 .. 可能就像在第二个查询中使用的那样。
标签: mysql indexing database-performance full-text-indexing