mysql不是唯一的自动递增,主键两个字段

mysql不是唯一的自动递增,主键两个字段

问题描述:

我想在MySQL中创建一个像这样的表结构:

I want to create a table structure like this in MySQL:

id  |  area    |  name 
----+----------+------------
1   |  name-1  |  test 
    |          |
1   |  name-1  | value2
    |          |
2   |  name-2  | test-value
    |          | 
3   |  name-3  | test
    |          |
3   |  name-3  | test

即.主键将是:primary_key( id, area )和id将是auto_increment,但是我只希望id对于每个新的唯一区域递增

ie. the primary key will be: primary_key( id, area ) and the id will be auto_increment, but i only want the id to increment for every new unique area

这可能吗?

您想要的东西是不可能的.您希望idarea作为主键,但是在您的示例中它们不是唯一的.

What you want is not possible. You want id and area to be the primary key but in your example they are not unique.

如果定义表键,则它必须是唯一的,并且在您的示例中,这意味着您需要在主键中包含name.但是为什么不只将id设置为主键并自动递增呢?这是常见用法.

If you define a table key it must be unique and in your example that would mean you need to include name in your primary key. But why not make just id the primary key and auto-increment it? That is the common usage.

例如,您可以创建一个名为area_id的额外字段.您可以将自动递增功能添加到字段中,如下所示:

You could create an extra field called area_id for instance. You can add the auto-increment functionality to the field likE this:

CREATE  TABLE `areas` 
(
  `id` INT NOT NULL ,
  `area_id` INT NOT NULL AUTO_INCREMENT ,
  `area` VARCHAR(100) NULL ,
  `name` VARCHAR(100) NULL ,
  PRIMARY KEY (`id`) 
);