MySQL creates primary key foreign key and composite primary key statements
- 2020-05-09 19:25:29
- OfStack
1. Create a primary key syntax
ALTER TABLE table_name ADD CONSTRAINT pk_name PRIMARY KEY(column name);
2. Create a foreign key syntax
ALTER TABLE news_info[subtable name] ADD CONSTRAINT ADD_news_info_news_type [constraint name] FOREIGN KEY (info_id)[subtable column] REFERENCES news_type[main table name] (id)[main table column];
3. Use a composite primary key
If one column cannot distinguish the records in one table by only one, consider combining multiple columns to achieve the uniqueness and form of distinguishing the table records
Create: create table sc (
studentno int,
courseid int,
score int,
primary key (studentno,courseid) );
When modified: alter table tb_name add primary key (field 1, field 2, field 3);
ALTER TABLE table_name ADD CONSTRAINT pk_name PRIMARY KEY(column name);
2. Create a foreign key syntax
ALTER TABLE news_info[subtable name] ADD CONSTRAINT ADD_news_info_news_type [constraint name] FOREIGN KEY (info_id)[subtable column] REFERENCES news_type[main table name] (id)[main table column];
3. Use a composite primary key
If one column cannot distinguish the records in one table by only one, consider combining multiple columns to achieve the uniqueness and form of distinguishing the table records
Create: create table sc (
studentno int,
courseid int,
score int,
primary key (studentno,courseid) );
When modified: alter table tb_name add primary key (field 1, field 2, field 3);