当前位置:   article > 正文

【MySQL】复合主键每个主键字段都能使用索引吗?可重复插入吗?_mysql一个字段同时是主键,也是普通索引可以吗

mysql一个字段同时是主键,也是普通索引可以吗

【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;
+--------+------------------+------+-----+---------+-------+
| Field  | Type             | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| id     | int
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/791898
推荐阅读
相关标签
  

闽ICP备14008679号