MySQL数据库优化的一些笔记

jerry mysql 2015年11月23日 收藏

0. 索引很重要

之前列举记录用了下面的语句。state字段为索引。

  1. SELECT * FROM feed_urls WHERE state='ok' AND feed_url<>'' LIMIT N,10

当记录数量很大时,有几万之后,这句SQL就很慢了。主要是因为feed_url没有建立索引。后来的解决方法是,把feed_url为空的,设为一个ok以外的state值,就行了。

1、索引不是万能的

为了计算记录总数,下面的语句会很慢。

  1. mysql> SELECT COUNT(*) FROM feed_urls WHERE state='error';
  2. +----------+
  3. | COUNT(*) |
  4. +----------+
  5. | 30715 |
  6. +----------+
  7. 1 row in set (0.14 sec)
  8.  
  9. mysql> EXPLAIN SELECT COUNT(*) FROM feed_urls WHERE state='error'\G
  10. *************************** 1. row ***************************
  11. id: 1
  12. select_type: SIMPLE
  13. table: feed_urls
  14. type: ref
  15. possible_keys: state,page_index
  16. key: page_index
  17. key_len: 10
  18. ref: const
  19. rows: 25936
  20. Extra: Using where; Using index
  21. 1 row in set (0.00 sec)

state为索引,请求用时140ms。遍历了state='error'索引下的每一条记录。

  1. mysql> SELECT state,COUNT(*) FROM feed_urls GROUP BY state;
  2. +----------+----------+
  3. | state | COUNT(*) |
  4. +----------+----------+
  5. | error | 30717 |
  6. | fetching | 8 |
  7. | nofeed | 76461 |
  8. | ok | 74703 |
  9. | queued | 249681 |
  10. +----------+----------+
  11. 5 rows in set (0.55 sec)
  12.  
  13. mysql> EXPLAIN SELECT state,COUNT(*) FROM feed_urls GROUP BY state\G
  14. *************************** 1. row ***************************
  15. id: 1
  16. select_type: SIMPLE
  17. table: feed_urls
  18. type: index
  19. possible_keys: NULL
  20. key: state
  21. key_len: 10
  22. ref: NULL
  23. rows: 431618
  24. Extra: Using index
  25. 1 row in set (0.00 sec)
  26.  

请求用时550ms。遍历了每个state下的每一条记录。

改进方法:

独立一个表用来计数,使用MySQL的Trigger同步计数:

  1. CREATE TRIGGER my_trigger AFTER UPDATE ON feed_urls
  2. FOR EACH ROW BEGIN
  3.  
  4. IF OLD.state <> NEW.state THEN
  5.  
  6. IF NEW.state='ok' THEN
  7. UPDATE feed_stat SET count_feed = count_feed + 1;
  8. END IF;
  9.  
  10. IF NEW.state IN ('ok', 'error', 'nofeed') THEN
  11. UPDATE feed_stat SET count_access = count_access + 1;
  12. END IF;
  13.  
  14. END IF;
  15.  
  16. END

2. 当分页很大时

  1. mysql> SELECT * FROM feed_urls LIMIT 230000, 1\G
  2. *************************** 1. row ***************************
  3. id: 736841f82abb0bc87ccfec7c0fdbd09c30b5a24d
  4. link: http://mappemunde.typepad.com/
  5. title: Tim Peterson
  6. feed_url: NULL
  7. update_time: 2012-05-12 11:01:56
  8. state: queued
  9. http_server: NULL
  10. abstract: NULL
  11. previous_id: ceea30e0ba609b69198c53ce71c44070d69038c5
  12. ref_count: 1
  13. error: NULL
  14. aid: 230001
  15. 1 row in set (0.50 sec)
  16.  
  17. mysql> EXPLAIN SELECT * FROM feed_urls LIMIT 230000, 1\G
  18. *************************** 1. row ***************************
  19. id: 1
  20. select_type: SIMPLE
  21. table: feed_urls
  22. type: ALL
  23. possible_keys: NULL
  24. key: NULL
  25. key_len: NULL
  26. ref: NULL
  27. rows: 431751
  28. Extra:
  29. 1 row in set (0.00 sec)

读取一条记录,耗时500ms,因为表记录是变长的,所以MySQL不能算出目标位置,只能每一条记录的数过去。

改进方法:

通过索引定位,数索引比数记录要快,因为索引占用的空间比整条记录小很多。

  1. mysql> SELECT * FROM (SELECT aid FROM feed_urls ORDER BY aid LIMIT 215000, 1) d JOIN feed_urls u ON d.aid=u.aid\G
  2. *************************** 1. row ***************************
  3. aid: 215001
  4. id: 2e4b1a385c8aae40b3ec2af9153805ca446f2029
  5. link: http://ncse.com/
  6. title: NCSE
  7. feed_url: NULL
  8. update_time: 2012-05-12 10:47:15
  9. state: queued
  10. http_server: NULL
  11. abstract: NULL
  12. previous_id: 819a6e3c5edc1624a9b8f171d8d3ae269843785f
  13. ref_count: 3
  14. error: NULL
  15. aid: 215001
  16. 1 row in set (0.06 sec)
  17.  
  18. mysql> EXPLAIN SELECT * FROM (SELECT aid FROM feed_urls ORDER BY aid LIMIT 215000, 1) d JOIN feed_urls u ON d.aid=u.aid\G
  19. *************************** 1. row ***************************
  20. id: 1
  21. select_type: PRIMARY
  22. table:type: system
  23. possible_keys: NULL
  24. key: NULL
  25. key_len: NULL
  26. ref: NULL
  27. rows: 1
  28. Extra:
  29. *************************** 2. row ***************************
  30. id: 1
  31. select_type: PRIMARY
  32. table: u
  33. type: const
  34. possible_keys: aid
  35. key: aid
  36. key_len: 4
  37. ref: const
  38. rows: 1
  39. Extra:
  40. *************************** 3. row ***************************
  41. id: 2
  42. select_type: DERIVED
  43. table: feed_urls
  44. type: index
  45. possible_keys: NULL
  46. key: aid
  47. key_len: 4
  48. ref: NULL
  49. rows: 211001
  50. Extra: Using index
  51. 3 rows in set (0.15 sec)

耗时60ms,比之前的方法快了将近10倍。如果LIMIT语句里还有WHERE a=1,应该建立一个(a,aid)的索引。

话说,MySQL好像还是不能直接算出第21500条索引的位置呀,这种方法还是数了索引了,能算出来就直接0ms了。不过这样的效率,对于百万级的,还能应付吧。如果是千万级的或者像我之前在KS创建的一张上亿条记录的表(120G),这种方法就肯定不行了。

经过上述优化,打开最后一页的速度已经很快了(之前需要800ms,现在则为300ms左右)。

膜拜下这Burst.NET最低档次的VPS (30RMB/month)。

  1. root@xiaoxia-pc:~/# ping feed.readself.com -n
  2. PING app.readself.com (184.82.185.32) 56(84) bytes of data.
  3. 64 bytes from 184.82.185.32: icmp_req=1 ttl=45 time=161 ms
  4. 64 bytes from 184.82.185.32: icmp_req=2 ttl=45 time=161 ms
  5. 64 bytes from 184.82.185.32: icmp_req=3 ttl=45 time=161 ms

用同样的方法,优化了搜索引擎的排名算法。即排名过程中选取尽量少的值出来排序,排序后再JOIN一次获取结果的信息。

排序过程如下:

  1. SELECT u.*, count_level(u.id) lv
  2. FROM(
  3. SELECT f.id, f.ref_count, MATCH(i.link,i.title) AGAINST (keywords) score
  4. FROM feed_index i
  5. JOIN feed_urls f ON f.id=i.id
  6. WHERE MATCH(i.link,i.title) AGAINST (keywords)
  7. ORDER BY score*0.5 + score*0.5*(ref_count/max_ref_count_in_result) DESC
  8. LIMIT offset,10
  9. ) d JOIN feed_urls u ON u.id = d.id

目前处理10万记录的全文索引数据,MySQL还是可以满足的,就是不知道上百万之后,还能不能撑下去。撑不下去就依赖第三方的工具了,例如Sphinx :)

3. SELECT里的函数

给FeedDB增加了层次的显示。因为本人太懒,所以没有给数据库表增加一个记录深度的字段。所以,直接写了一个MySQL的自定义函数 count_level,用来统计通过parent_id一直找到顶层经过的路径长度(Level)。

  1. CREATE DEFINER=`feeddb_rw`@`%` FUNCTION `count_level`(fid char(40)) RETURNS int(11)
  2. BEGIN
  3. SET @levels = 0;
  4. SET @found = false;
  5. WHILE NOT @found DO
  6. SELECT previous_id INTO @prev_id FROM feed_urls WHERE id=fid;
  7. IF @prev_id is null OR @prev_id = '' THEN
  8. SET @found = true;
  9. ELSE
  10. SET @levels = @levels + 1;
  11. SET fid = @prev_id;
  12. END IF;
  13. END WHILE;
  14. IF @prev_id is null THEN
  15. RETURN null;
  16. END IF;
  17. RETURN @levels;
  18. END

在网页显示的时候用了类似下面的SQL语句。

  1. mysql> SELECT u.*, count_level(u.id) FROM feed_urls u ORDER BY ref_count DESC LIMIT 12000,1\G
  2. *************************** 1. row ***************************
  3. id: e42f44b04dabbb9789ccb4709278e881c54c28a3
  4. link: http://tetellita.blogspot.com/
  5. title: le hamburger et le croissant
  6. feed_url: http://www.blogger.com/feeds/7360650/posts/default
  7. update_time: 2012-05-15 14:50:53
  8. state: ok
  9. http_server: GSE
  10. abstract: Lepekmezest un épais sirop bordeaux obtenu par réduction dumoût de raisin, une sorte de mélasse de raisin, en somme. Légèrement acidulé, il apporte du pep's aux yaourts et nappe avec bonheur les
  11. previous_id: 129cabd96e7099a53b78c7ddeff98658351082e9
  12. ref_count: 9
  13. error: NULL
  14. aid: 174262
  15. count_level(u.id): 8
  16. 1 row in set (4.10 sec)

好吧,悲剧了!4100ms。一定对12000个条目都算了一次count_level,然后再进行排序。所以才用上了4秒那么漫长的时间!!!

改进方法:

先SELECT LIMIT,再在派生的临时表里,计算count_level。

  1. mysql> SELECT u.*, count_level(u.id) FROM (
  2. SELECT id FROM feed_urls ORDER BY ref_count DESC LIMIT 27521,1
  3. ) d JOIN feed_urls u ON u.id=d.id\G
  4. *************************** 1. row ***************************
  5. id: 61df288dda131ffd6125452d20ad0648f38abafd
  6. link: http://mynokiamobile.org/
  7. title: My Nokia Mobile
  8. feed_url: http://mynokiamobile.org/feed/
  9. update_time: 2012-05-14 14:06:57
  10. state: ok
  11. http_server: Apache/2.2.19 (Unix) mod_ssl/2.2.19 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635
  12. abstract: ArchivesSelect MonthMay 2012April 2012March 2012February 2012January 2012December 2011November 2011October 2011September 2011August 2011July 2011June 2011May 2011April 2011March 2011February 2011Janua
  13. previous_id: f37af92bb89c08f6d4b69e72eab05d8ab1e2aca4
  14. ref_count: 5
  15. error: NULL
  16. aid: 154996
  17. count_level(u.id): 8
  18. 1 row in set (0.09 sec)

如此,优化之后效果好很多了!但是还可以继续优化,例如建立一个字段存储Level的值应该是最好的办法了。