Composite primary key and the primary key

  Today electric plane asked a question composite primary key, hit his knowledge blind spot, then the answer is added with ALTER TABLE ADD PRIMARY KEY, then check under the right answer, just by the opportunity to put the primary key is also under review .


  First talk about the primary key, the primary key is actually the middle of the table. In many-to-model, the primary key of the composition requires two tables primary key, so that each data can be found in the two tables, the following Example:

The CREATE  TABLE TEAM ( 
Id MEDIUMINT the AUTO_INCREMENT the COMMENT ' master key ' , 
Dev VARCHAR ( 30 ) the COMMENT ' code farmers ' , 
Pm is VARCHAR ( 30 ) the COMMENT ' project manager ' , 
Hr of VARCHAR ( 30 ) the COMMENT ' human ' , 
 a PRIMARY  KEY (Id) 
) 
ENGINE = INNODB, 
the CHARSET = the UTF8;
The CREATE  TABLE Information ( 
Id MEDIUMINT the AUTO_INCREMENT the COMMENT ' master key ' , 
the Name VARCHAR ( 30 ) the COMMENT ' name ' , 
Age int ( 10 ) the COMMENT ' aged ' ,
 a PRIMARY  KEY (Id) 
) 
ENGINE = INNODB, 
the CHARSET = the UTF8;

To query element between the two tables, we create an intermediate table TEAM_info

CREATE TABLE IF NOT EXISTS TEAM_info(
Id MEDIUMINT AUTO_INCREMENT COMMENT '主键Id',
TEAM_Id MEDIUMINT COMMENT '团队Id',
info_Id MEDIUMINT COMMENT '信息Id',
PRIMARY KEY(Id) 
)
ENGINE=INNODB,
CHARSET=UTF8;

Then you can connect the intermediate table by table lookup operation.


  Next is the composite primary key, a table can have only one primary key, but if necessary, we can set up more than one field at the same time as the primary key, which is called the composite primary key. (PS: I like people translated into the primary key, I personally feel very accurate, easy to confuse) For example, we create a table

CREATE TABLE IF NOT EXIST student(
Name VARCHAR (30 ) COMMENT '姓名',
Age INT(30)  COMMENT '年龄',
PRIMARY KEY(Name,Age) 
);

Name and Age here is a composite primary key field, mainly in order to prevent duplicate Name, Age and Name thus provided a composite primary key field length and number of primary key fields to be better. Here is a note that point then, if you want to set the primary key in INNODB engine from growth, since growth must be listed in the first column, and then only need to specify the column non-self-growth on it, there would be an increase from repeating. Once the self-growth appear to repeat the words, we can create a primary key index, or unique index. If the table structure already exists, add the desired composite primary key should be used in the following manner.

ALTER TABLE tb_name 
ADD PRIMARY KEY (
PRIMARY_KEY_NAME_1,
PRIMARY_KEY_NAME_2
);

 

It should be noted here need the original table structure where no primary key, if any, need to ALTER DROP off the original primary key, and then add the composite primary key inside.

 

Guess you like

Origin www.cnblogs.com/CNty/p/10941398.html