错误“PRIMARY KEY必须包含表格分区功能中的所有列”

时间:2016-02-20 15:35:57

标签: mysql indexing partitioning

在列country_id上添加分区索引到下表时,我收到错误:

  

PRIMARY KEY必须包含表格分区中的所有列   功能

我尝试将列country_id添加到包含id和country_id的PK中。但随后会出现类似的错误消息:

  

UNIQUE KEY必须包含表分区中的所有列   功能

CREATE TABLE `geo_city` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `country_id` smallint(5) unsigned NOT NULL,
  `admin_zone_id` bigint(20) unsigned DEFAULT NULL,
  `name` varchar(128) NOT NULL,
  `lat` double NOT NULL,
  `lng` double NOT NULL,
  `population` int(10) unsigned DEFAULT NULL,
  `timezone_id` smallint(5) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_city_id_per_country` (`id`,`country_id`),
  UNIQUE KEY `idx_unique_city_per_adminzone` (`admin_zone_id`,`name`),
  KEY `country_id` (`country_id`),
  KEY `name` (`name`),
  KEY `idx_lat_lng` (`lat`,`lng`),
  KEY `admin_zone_id` (`admin_zone_id`),
  KEY `population` (`population`),
  KEY `timezone_id` (`timezone_id`)
) ENGINE=InnoDB AUTO_INCREMENT=496831 DEFAULT CHARSET=utf8;

然后:

ALTER TABLE geo.geo_city PARTITION BY RANGE (country_id) (
                PARTITION p0 VALUES LESS THAN (2),
                PARTITION p1 VALUES LESS THAN (10),
                PARTITION p2 VALUES LESS THAN (20),
                PARTITION p3 VALUES LESS THAN (30),
                PARTITION pRemain VALUES LESS THAN MAXVALUE
            )

现在该怎么办?

2 个答案:

答案 0 :(得分:1)

尝试这个定义:

CREATE TABLE `geo_city` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `country_id` smallint(5) unsigned NOT NULL,
  `admin_zone_id` bigint(20) unsigned DEFAULT NULL,
  `name` varchar(128) NOT NULL,
  `lat` double NOT NULL,
  `lng` double NOT NULL,
  `population` int(10) unsigned DEFAULT NULL,
  `timezone_id` smallint(5) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`, country_id),
  UNIQUE KEY `idx_unique_city_per_adminzone` (`admin_zone_id`,`name`, country_id),
  KEY `name` (`name`),
  KEY `idx_lat_lng` (`lat`,`lng`),
  KEY `admin_zone_id` (`admin_zone_id`),
  KEY `population` (`population`),
  KEY `timezone_id` (`timezone_id`)
) ENGINE=InnoDB AUTO_INCREMENT=496831 DEFAULT CHARSET=utf8;

如错误所示,每个唯一键都需要包含country_id。注意:我不相信country_id确实是分区的好选择,因为各国的规模差别很大。但是,问题不在于您的特定分区方案的优点。

答案 1 :(得分:0)

您需要将所有分区键添加到所有主键和唯一键中。