Search code examples
mysqlprimary-keyuniqueauto-increment

mysql not unique auto increment, primary key two fields


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?


Solution

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