mysql not unique auto increment, primary key two fields

假如想象 提交于 2019-12-24 05:43:34

问题


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

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

is this possible?


回答1:


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

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.

EDIT :

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`) 
);


来源:https://stackoverflow.com/questions/8694064/mysql-not-unique-auto-increment-primary-key-two-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!