一句Sql语句的优化(带子查询)
SELECT * FROM `threads` where `createbyid` <> 24016 AND `id` in (SELECT `threadid` FROM `thread_replys` WHERE `userid` = 24016 GROUP BY `threadid`);
这么一句sql,要想高效,应该怎么写?
SELECT * FROM `threads` where `createbyid` <> 24016 AND `id` in (SELECT `threadid` FROM `thread_replys` WHERE `userid` = 24016 GROUP BY `threadid`);
这么一句sql,要想高效,应该怎么写?
CREATE TABLE `threads` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '',
`content` blob NOT NULL,
`createby` varchar(50) NOT NULL DEFAULT '',
`createbyid` int(11) NOT NULL,
`lastreply` varchar(50) NOT NULL DEFAULT '',
`lastreplyid` int(11) NOT NULL DEFAULT '0',
`createdate` int(11) NOT NULL,
`updatedate` int(11) NOT NULL,
`replys` int(11) NOT NULL,
`modifydate` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1540 DEFAULT CHARSET=utf8;
EXPALIN的结果
mysql> explain
-> SELECT * FROM `threads` where `createbyid` <> 24016 AND `id` in (SELECT `threadid` FROM `thread_replys` WHERE `userid` = 24016 GROUP BY `threadid`);
+----+--------------------+---------------+-------+---------------+----------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+---------------+-------+---------------+----------+---------+------+------+-------------+
| 1 | PRIMARY | threads | ALL | createbyid | NULL | NULL | NULL | 1505 | Using where |
| 2 | DEPENDENT SUBQUERY | thread_replys | index | NULL | threadid | 5 | NULL | 6 | Using where |
+----+--------------------+---------------+-------+---------------+----------+---------+------+------+-------------+
2 rows in set (0.00 sec)