我想從一個表格中獲得用戶的數量,這個表格有22m行。mysql COUNT()num rows too slow
我的SQL如下:
SELECT
COUNT(id)
FROM
subscribers
WHERE
suid=541839243781
這就需要12.6020小號加載
但是後面相同的查詢(得到了用戶的訂閱)只0.0036小號加載需要(似乎確定)
SELECT
COUNT(uid)
FROM
subscribers
WHERE
uid=541839243781
我解釋一下:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE dvx_subscribers index 4 4 16 NULL 22041275 Using where; Using index
SHOW CREATE TABLE:
CREATE TABLE `subscribers` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`sid` bigint(20) unsigned NOT NULL,
`uid` bigint(20) unsigned NOT NULL,
`suid` bigint(20) unsigned NOT NULL,
`date` datetime NOT NULL,
KEY `id` (`id`),
KEY `2` (`uid`,`suid`),
KEY `4` (`suid`,`id`)
) ENGINE=MyISAM AUTO_INCREMENT=23226599 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
指標:
Table Non_unique Key_name Seq_in_index Column_name Collation Cardinality Sub_part Packed Null Index_type Comment
subscribers 1 id 1 id A NULL NULL NULL BTREE
subscribers 1 2 1 uid A 449821 NULL NULL BTREE
subscribers 1 2 2 suid A 459193 NULL NULL BTREE
subscribers 1 4 1 suid A 6115 NULL NULL BTREE
subscribers 1 4 2 id A 22041275 NULL NULL BTREE
我怎樣才能索引它或優化它儘可能快加載儘可能?導致12secs對此太多了......
僅在'id'和'suid'或'suid'上創建一個索引。 – 2012-04-19 17:37:16
@DanielKamilKozar。爲什麼只有'suid'? (Upvoted答案,你省略了...) – gdoron 2012-04-19 17:41:50
是4秒不變或它變化? – 2012-04-19 18:36:24