clintgh
clintgh

Reputation: 2077

Combination of columns as table's primary key

Is it possible to make a combination of columns a table's primary key?
For example I have:

ID_1 | ID_2 | ID_3 | ID_4 | VALUE ----- ------ ------ ------ ------ 1 1 1 1 A 1 2 1 1 B 2 1 1 1 A

I want the values of ID_1, ID_2, ID_3 and ID_4 combined to be the primary key. Thanks

Upvotes: 0

Views: 240

Answers (2)

user3522371
user3522371

Reputation:

-First solution:

  CREATE TABLE IF NOT EXISTS tableName (    
       id_1 INT NOT NULL,
       id_2 INT NOT NULL,
       id_3 INT NOT NULL,
       id_4 INT NOT NULL,
       value VARCHAR(10) NULL,
       CONSTRAINT pk PRIMARY KEY (id_1, id_2, id_3, id_4)
    );

-Second solution: Use association tables.

Upvotes: 1

K.I.
K.I.

Reputation: 807

It is possible, but should be avoided. Primary key should be one column.

CREATE TABLE `test`.`new_table` (
  `id_1` INT NOT NULL,
  `id_2` INT NOT NULL,
  `id_3` INT NOT NULL,
  `id_4` INT NOT NULL,
  `value` VARCHAR(45) NULL,
  PRIMARY KEY (`id_1`, `id_2`, `id_3`, `id_4`));

Upvotes: 0

Related Questions