Two column as a primary keys in mysql?

前端 未结 8 1709
孤独总比滥情好
孤独总比滥情好 2020-12-15 06:34

Today I found out you can have a primary key using two columns (tsql). The PK must be unique but both columns do not (the combo must be unique).

I thought that was v

8条回答
  •  抹茶落季
    2020-12-15 06:55

    To make it easier to explain, I will only use one table. Create a table with 2 int columns, and a PK on both of them together. As in the question.

    create table test(
      a  INT  NOT NULL ,
      b  INT  NOT NULL ,
      PRIMARY KEY(a,b));
    

    Now we can add rows, until we get an error

    insert into test values(1,1); 
    Query OK, 1 row affected (0,00 sec)
    
    insert into test values(1,2); 
    Query OK, 1 row affected (0,00 sec)
    
    insert into test values(1,1); 
    ERROR 1062 (23000): Duplicate entry '1-1' for key 'PRIMARY'
    

    Which is logical because the combined values of the 2 columns which make up the PK are not unique anymore when this last statement would be executed.

    It is allowed to store 2x the value 1 in a, because that is not the PK. The PK is the combined value of columns a and b.

提交回复
热议问题