我已经设置了我的新闻脚本,因此它将显示最新的 5 个帖子(与当前查看的帖子属于同一类别 - 不包括当前查看的帖子)。
我的 SQL 看起来像这样:
SELECT title, sid, url, category
FROM news
WHERE category = ? AND sid <> ? ORDER BY sid DESC LIMIT 5
这是查询的解释:
+----+-------------+----------+------+------------------+----------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------+------+------------------+----------+---------+-------+------+-------------+
| 1 | SIMPLE | news | ref | PRIMARY,category | category | 98 | const | 154 | Using where |
+----+-------------+----------+------+------------------+----------+---------+-------+------+-------------+
1 row in set (0.00 sec)
我想知道的是 - 有没有办法优化我的查询,所以它不必扫描这么多行来获得 5 个结果?
编辑
类别索引的结果:
mysql> EXPLAIN EXTENDED SELECT title, sid, url, category FROM news WHERE category = ? AND sid <> ? ORDER BY sid DESC LIMIT 5\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: news
type: ref
possible_keys: PRIMARY,category
key: category
key_len: 98
ref: const
rows: 156
filtered: 100.00
Extra: Using where
1 row in set, 1 warning (0.00 sec)
没有类别索引的结果:
mysql> EXPLAIN EXTENDED SELECT title, sid, url, category FROM news WHERE category = ? AND sid <> ? ORDER BY sid DESC LIMIT 5\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: news
type: index
possible_keys: PRIMARY
key: PRIMARY
key_len: 2
ref: NULL
rows: 5
filtered: 7420.00
Extra: Using where
1 row in set, 1 warning (0.00 sec)