如何用两个索引对MySQL表进行分区

时间:2013-03-26 03:23:08

标签: mysql innodb partitioning database-partitioning

我的表格game_log包含字段idgame_id和多个varchar字段。

id是主键,game_id是非唯一键。

经常有两个问题:

SELECT * FROM game_log ORDER BY id DESC LIMIT 20
SELECT * FROM game_log WHERE game_id = <value> ORDER BY id DESC

表格很大(6.1GB和32M行)。 InnoDB的。其中的行是随机添加的(每个查询一个)。此外,一些游戏正在被删除。

我需要减少磁盘IO并降低响应速度。

我应该使用key还是range分区?如果range,则按idgame_id?有没有理论?

1 个答案:

答案 0 :(得分:4)

按范围使用分区。

如果按键分区,则两个示例查询都必须触及每个分区。

理论上,通过KEY进行分区就像是通过散列进行分区,因为主键的连续值必须存储在单独的分区中。通过查询一系列id值,可以破坏分区修剪。

演示:

CREATE TABLE `game_log` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `game_id` int(11) NOT NULL DEFAULT '0',
  `xyz` varchar(15) DEFAULT NULL,
  PRIMARY KEY (`id`,`game_id`)
) 
PARTITION BY KEY ()
PARTITIONS 13;

INSERT INTO game_log (game_id) VALUES (1), (2), (3), (4), (5), (6);

EXPLAIN PARTITIONS SELECT * FROM game_log ORDER BY id DESC LIMIT 3\G
           id: 1
  select_type: SIMPLE
        table: game_log
   partitions: p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12

EXPLAIN PARTITIONS SELECT * FROM game_log WHERE game_id = 4 ORDER BY id DESC LIMIT 3\G
           id: 1
  select_type: SIMPLE
        table: game_log
   partitions: p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12

然而,如果你在game_id上​​按范围进行分区,那么至少在查询特定的game_id时,你可以通过分区修剪来帮助你。但是你对id desc的任何game_id命令的查询仍然会触及每个分区。

CREATE TABLE `game_log` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `game_id` int(11) NOT NULL DEFAULT '0',
  `xyz` varchar(15) DEFAULT NULL,
  PRIMARY KEY (`id`,`game_id`)
)
PARTITION BY RANGE (game_id)
(PARTITION p1 VALUES LESS THAN (3),
 PARTITION p2 VALUES LESS THAN (6),
 PARTITION p3 VALUES LESS THAN MAXVALUE);

INSERT INTO game_log (game_id) VALUES (1), (2), (3), (4), (5), (6);

EXPLAIN PARTITIONS SELECT * FROM game_log ORDER BY id DESC LIMIT 3\G
           id: 1
  select_type: SIMPLE
        table: game_log
   partitions: p1,p2,p3

EXPLAIN PARTITIONS SELECT * FROM game_log WHERE game_id = 4 ORDER BY id DESC LIMIT 3\G
           id: 1
  select_type: SIMPLE
        table: game_log
   partitions: p2