Home  >  Article  >  Database  >  How to set a composite primary key for a table in MySQL?

How to set a composite primary key for a table in MySQL?

黄舟
黄舟Original
2017-08-02 13:46:4517203browse

#Mysql sometimes encounters multiple fields to represent the uniqueness of data, so a composite primary key will be used here.

Recommended related mysql video tutorials: "mysql tutorial"

##1. Write the sql code to create the table ;

How to set a composite primary key for a table in MySQL?

2. Set the joint primary key;

How to set a composite primary key for a table in MySQL?

##3. Execute the code and find an error;

How to set a composite primary key for a table in MySQL?

4. Solution: Increment the id Add UNIQUE unique index to the column;

How to set a composite primary key for a table in MySQL?##5. The code is executed successfully;

How to set a composite primary key for a table in MySQL?#6. The joint primary key is created successfully.

How to set a composite primary key for a table in MySQL?7.SQL sample code:

USE test
CREATE TABLE `test_table` (
  `id` INT(11) NOT NULL AUTO_INCREMENT UNIQUE COMMENT '自增',
  `realName` VARCHAR(50) CHARACTER SET gbk DEFAULT NULL COMMENT '真实姓名',
  `area_id` VARCHAR(50) CHARACTER SET gbk DEFAULT NULL COMMENT '地区编号',
  `enter_time` INT(11) DEFAULT NULL COMMENT '录入时间',
  `mark` VARCHAR(60) CHARACTER SET gbk DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`realName`,`area_id`)
) ENGINE=MYISAM AUTO_INCREMENT=1133 DEFAULT CHARSET=gbk;

The above is the detailed content of How to set a composite primary key for a table in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn