设置方法:在“create table”语句中,通过“primary key”关键字来指定主键,语法格式“字段名 数据类型 primary key [默认值]”或“[constraint 约束名] primary key 字段名”。
主键(primary key)的完整称呼是“主键约束”,是 mysql 中使用最为频繁的约束。一般情况下,为了便于 dbms 更快的查找到表中的记录,都会在表中设置一个主键。
(推荐教程:mysql视频教程)
在创建表时设置主键约束在创建数据表时设置主键约束,既可以为表中的一个字段设置主键,也可以为表中多个字段设置联合主键。但是不论使用哪种方法,在一个表中主键只能有一个。下面分别讲解设置单字段主键和多字段联合主键的方法。
1)设置单字段主键
在 create table 语句中,通过 primary key 关键字来指定主键。
在定义字段的同时指定主键,语法格式如下:
<字段名> <数据类型> primary key [默认值]
例 1
在 test_db 数据库中创建 tb_emp3 数据表,其主键为 id,sql 语句和运行结果如下。
mysql> create table tb_emp3 -> ( -> id int(11) primary key, -> name varchar(25), -> deptid int(11), -> salary float -> );query ok, 0 rows affected (0.37 sec)mysql> desc tb_emp3;+--------+-------------+------+-----+---------+-------+| field | type | null | key | default | extra |+--------+-------------+------+-----+---------+-------+| id | int(11) | no | pri | null | || name | varchar(25) | yes | | null | || deptid | int(11) | yes | | null | || salary | float | yes | | null | |+--------+-------------+------+-----+---------+-------+4 rows in set (0.14 sec)
或者是在定义完所有字段之后指定主键,语法格式如下:
[constraint <约束名>] primary key [字段名]
例 2
在 test_db 数据库中创建 tb_emp4 数据表,其主键为 id,sql 语句和运行结果如下。
mysql> create table tb_emp4 -> ( -> id int(11), -> name varchar(25), -> deptid int(11), -> salary float, -> primary key(id) -> );query ok, 0 rows affected (0.37 sec)mysql> desc tb_emp4;+--------+-------------+------+-----+---------+-------+| field | type | null | key | default | extra |+--------+-------------+------+-----+---------+-------+| id | int(11) | no | pri | null | || name | varchar(25) | yes | | null | || deptid | int(11) | yes | | null | || salary | float | yes | | null | |+--------+-------------+------+-----+---------+-------+4 rows in set (0.14 sec)
2)在创建表时设置联合主键
所谓的联合主键,就是这个主键是由一张表中多个字段组成的。
比如,设置学生选课数据表时,使用学生编号做主键还是用课程编号做主键呢?如果用学生编号做主键,那么一个学生就只能选择一门课程。如果用课程编号做主键,那么一门课程只能有一个学生来选。显然,这两种情况都是不符合实际情况的。
实际上设计学生选课表,要限定的是一个学生只能选择同一课程一次。因此,学生编号和课程编号可以放在一起共同作为主键,这也就是联合主键了。
主键由多个字段联合组成,语法格式如下:
primary key [字段1,字段2,…,字段n]
注意:当主键是由多个字段组成时,不能直接在字段名后面声明主键约束。
例 3
创建数据表 tb_emp5,假设表中没有主键 id,为了唯一确定一个员工,可以把 name、deptid 联合起来作为主键,sql 语句和运行结果如下。
mysql> create table tb_emp5 -> ( -> name varchar(25), -> deptid int(11), -> salary float, -> primary key(id,deptid) -> );query ok, 0 rows affected (0.37 sec)mysql> desc tb_emp5;+--------+-------------+------+-----+---------+-------+| field | type | null | key | default | extra |+--------+-------------+------+-----+---------+-------+| name | varchar(25) | no | pri | null | || deptid | int(11) | no | pri | null | || salary | float | yes | | null | |+--------+-------------+------+-----+---------+-------+3 rows in set (0.14 sec)
相关推荐:php培训
以上就是mysql建表时怎么设置主键?的详细内容。