【MySQL】复合主键每个主键字段都能使用索引吗?可重复插入吗?
文章目录
一、主键
primary key用来唯一约束该字段里面的数据。其主要特征有:
● 不能重复,不能为空
● 一张表中最多只有一个primary key
● primary key 所在列通常是整数类型
1.1 创建主键
create table [表名] ([字段1] [字段类型1] primary key,[字段2] [字段类型2], …);
create table [表名] ([字段1] [字段类型1],[字段2] [字段类型2], … ,primary key(字段));
alter table [表名] add primary key(字段);
1.2 删除主键
alter table [表名] drop primary key;
二、复合主键
在创建表的时候,在所有字段之后,使用primary key(字段)
来创建主键,如果有多个字段作为主键,可以使用符合主键。
MariaDB [class_info]> create table test(
id int unsigned,course char(10) comment '课程代码',
score int unsigned default 60 comment '成绩',
primary key(id,course));
Query OK, 0 rows affected (0.01 sec)
MariaDB [class_info]> show create table test\G
*************************** 1. row ***************************
Table: test
Create Table: CREATE TABLE `test` (
`id` int(10) unsigned NOT NULL DEFAULT '0',
`course` char(10) NOT NULL DEFAULT '' COMMENT '课程代码',
`score` int(10) unsigned DEFAULT '60' COMMENT '成绩',
PRIMARY KEY (`id`,`course`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
MariaDB [class_info]> desc test;
+--------+------------------+------+-----+---------+-------+
|