MySQL实战篇:创建表table,主键,外键!如何创建?

【总论:创建表的语法】
create table 表名
(字段名 数据类型 字段属性,
.....);
1.创建tb_emp2表,其主键为id

主键:primary key对字段具有非空和唯一约束
<1>第1种方法
create table tb_emp2
(id int(11) not null primary key,
name varchar(25) not null,
depId int(11),
salary float);

<2>第二种方法
create table tb_emp2
(id int(11) not null ,
name varchar(25) not null,
depId int(11),
salary float,
primary key(id));

2.定义数据表tb_emp4,假设表中没有id,为了唯一确定一个员工,可以把name,depId联合起来作为主键。

create table tb_emp4
(name varchar(25) not null,
depId int(11) not null,
salary float,
primary key(name,depId));

3.定义数据表tb_emp5,并在tb_emp5表上创建外键约束,让tb_empId作为关键关联到tb_empt1的主键id。
<1>tb_empId表

<2>tb_emp5表

<3>普通索引:key|index
<4>MUL不是外键的标识,而是索引的标识。
<5>外键:foreign key
(1)constraint 外键名 foreign key(字段名)references 表名(字段名)
(2)foreign key(字段名)references 表名(字段名)
create table tb_emp5
(id int(11) not null primary key,
name varchar(22),
deptId int(11),
salary float,
constraint fk_ed foreign key(deptId) references tb_dept1(id));

相关推荐
-
「nginx」十、nginx的location配置详解2026-07-04 00:51:45 -

最清晰的mysql体系架构图 ,助你深度掌握MySQL开发管理,赢在大数据时代
最清晰的mysql体系架构图 ,助你深度掌握MySQL开发管理,赢在大数据时代2026-07-04 00:21:47 -
PHP读取Excel内的图片2026-07-03 00:07:41 -
mysql:Otter跨机房数据同步(单向)2026-07-03 00:02:48 -

在windows10系统下搭建IIS+PHP+MYSQL+phpMyAdmin服务器运行环境
在windows10系统下搭建IIS+PHP+MYSQL+phpMyAdmin服务器运行环境2026-07-02 00:15:08