回答

收藏

MySQL索引配置

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

我上有4500万行新闻。表架构如下:
0 I& [* V7 z+ h4 z- L, HCREATE 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秒以上:
. K# l) ?1 n) _2 i) ^select * news where cat_id='4' order by id desc limit 150000,10;说明显示其使用 where和索引 cat_id_2”
' }, m  \$ |# c% d+ s! N在写这个问题的时候,我也检查了一个更简单的问题sql查询也花了将近一分钟:
3 z: \- \8 z. a5 C7 lselect * from haberler order by id desc limit 40000,10;如果sql类似于以下内容,只需几毫秒:
% k( f1 Z. g! r' b" Rselect * from haberler order by id desc limit 20,10;我的my.cnf配置如下:- p: s3 r& {  C2 [/ Y% j) c
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但我不确定。提前感谢。5 ~* Z# Y( J$ I
                                                               
( D8 z( x. |/ g& {+ o3 `' I' w7 u    解决方案:                                                                1 h! U2 J: Z  p* y# n6 z' s
                                                                更新:, {. k7 p; m1 d5 X7 [; o8 D
请参阅我的博客中的这篇文章,以便更详细地分析问题:3 p6 x8 A0 R4 Q/ Y) w/ k4 |
MySQL ORDER BY / LIMIT性能:晚行搜索当您发送类似内容时LIMIT 1.5万,10意味着MySQL记录这些150000,并查找下一个10。, v* E1 d: b3 C& X
中遍历索引非常慢MySQL。
3 {; }1 {  L6 P) c3 P. _* Q同样,MySQL以后不能搜索。- z) u9 _3 o2 I& E  t
理论上,如果你这样做的话ORDER BY id LIMIT 1万,10,足以用索引找到1万到1万的价值观,然后看到只有10满足该指数并返回它们。' s1 C4 ~% H6 m
除主要值外MySQL,所有主要系统都会意识到这一点,只有在确实需要返回值时才能向上搜索。
" t: z# i3 Z" v; U  U! p  j/ IMySQL,但是,每行都要找一次。
' X+ s+ ?5 s3 D$ Z6 @/ @试着这样重写查询:  d4 _8 H* g- t" q" v
SELECT  news.*FROM    (            SELECT  id        FROM    news        WHERE   cat_id=  ORDER BY                id DESC        LIMIT            oJOIN    newsON      news.id = o.id
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则