回答

收藏

MySQL索引配置

技术问答 技术问答 503 人阅读 | 0 人回复 | 2023-09-14

我上有4500万行新闻。表架构如下:; @+ E/ [1 ?8 ]$ W3 J6 d) ^
CREATE TABLE IF NOT EXISTS `news` (  `id` int(11) NOT NULL auto_increment, `cat_id` int(11) NOT NULL, `title` tinytext NOT NULL, `content` text NOT NULL, `date` int(11) NOT NULL, `readcount` int(11) NOT NULL default '0', PRIMARY KEY  (`id`), KEY `cat_id` (`cat_id`), KEY `cat_id_2` (`cat_id`,`id`), KEY `cat_id_date` (`cat_id`,`date`)) ENGINE=MyISAM  DEFAULT CHARSET=latin5 AUTO_INCREMENT=462679 ;如下所示,示sql命令获取类别页面的页面 x一些消息,如果x超过100秒需要15秒以上:
. h, r# y, |* ~# p; kselect * news where cat_id='4' order by id desc limit 150000,10;说明显示其使用 where和索引 cat_id_2”5 d+ K6 S9 W9 J7 p5 z
在写这个问题的时候,我也检查了一个更简单的问题sql查询也花了将近一分钟:
9 t7 ]6 X* W- J# i) Oselect * from haberler order by id desc limit 40000,10;如果sql类似于以下内容,只需几毫秒:
' V) ^* d+ j. c- m6 }% oselect * from haberler order by id desc limit 20,10;我的my.cnf配置如下:4 |9 r/ v4 ^0 ]' [2 R; E: \; Y) G
skip-lockingskip-innodbquery_cache_limit=1Mquery_cache_size=256Mquery_cache_type=1max_connections=30interactive_timeout=600000#wait_timeout=5#connect_timeout=5thread_cache_size=384key_buffer=256Mjoin_buffer=4Mmax_allowed_packet=16Mtable_cache=1024record_buffer=1Msort_buffer_size=64Mread_buffer_size=16Mmax_connect_errors=10# Try number of CPU's*2 for thread_concurrencythread_concurrency=2myisam_sort_buffer_size=128Mlong_query_time         = 1log_slow_queries        = /var/log/mysql/mysql-slow.logmax_heap_table_size=512M该网站运行在2GB RAM的core2duo上去。我认为问题可能是由于sort_buffer_size但我不确定。提前感谢。
0 u9 L, |3 k8 ]6 o                                                               
/ h; n- F) c, \3 k    解决方案:                                                                $ [& O* s! {* K  R, {5 q) m- K
                                                                更新:% |: x- x+ N) b# P' q
请参阅我的博客中的这篇文章,以便更详细地分析问题:
6 I5 G2 I2 `  d3 c; nMySQL ORDER BY / LIMIT性能:晚行搜索当您发送类似内容时LIMIT 1.5万,10意味着MySQL记录这些150000,并查找下一个10。
. p# ]/ x2 B( D8 P6 n  D! i/ n$ \/ k中遍历索引非常慢MySQL。% M! o! e) d2 d% y5 Q7 d5 Z
同样,MySQL以后不能搜索。0 n! t" |% G( P( @( N$ F3 K( w
理论上,如果你这样做的话ORDER BY id LIMIT 1万,10,足以用索引找到1万到1万的价值观,然后看到只有10满足该指数并返回它们。7 m( ^7 v' E1 ?# s1 H) o* T
除主要值外MySQL,所有主要系统都会意识到这一点,只有在确实需要返回值时才能向上搜索。
3 [, f# r. S* QMySQL,但是,每行都要找一次。
9 k& U1 m- g; \5 K7 U/ e9 b8 J试着这样重写查询:
1 l2 t! e: F. R" F  PSELECT  news.*FROM    (            SELECT  id        FROM    news        WHERE   cat_id=  ORDER BY                id DESC        LIMIT            oJOIN    newsON      news.id = o.id
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则