创建表
建议:创建数据表之前,应该首先使用【use database_name】指定是在哪个数据库中进行
语法:
create table [if not exists] 表名 (
字段名1 数据类型 [列级别约束条件] [默认值],
字段名2 数据类型 [列级别约束条件] [默认值],
...
[表级别约束条件]
);
-- 表名称不区分大小写;不能使用 SQL 语言中的关键字,比如:drop、alter、insert等
e.g.:
create table if not exists tb_emp1(
id int(11),
name varchar(25),
dept_id int(11),
salary float
);
-- show tables 查看
约束
主键约束
主键约束:Primary Key Constraint;主键列数据唯一,非空;唯一标志,定义表关系,加快查询速度
类型:
单字段主键
多字段联合主键
单字段主键:
语法:
-- 在定义列的同时指定主键
-- 字段名 数据类型 primary key [默认值]
create table if not exists tb_emp2(
id int(11) **primary key**,
name varchar(25),
dept_id int(11),
salary float
);
-- 在定义完所有列后指定主键
-- [constraint ] primary key [字段名]
create table if not exists tb_emp3(
id int(11),
name varchar(25),
dept_id int(11),
salary float,
**primary key(id)**
);
多字段联合主键
语法:
-- primary key [字段1, 字段2, ... , 字段n]
create table tb_emp4(
name varchar(25),
dept_id int(11),
salary float,
primary key(name,dept_id)
)
外键约束
外键约束:在表的数据之间建立连接关系,可以一列或者多列;对应的是参照完整性;定义了外键后,不允许删除在另一个表中鞠永关联关系的行
作用:保证数据引用的一致性、完整性;
语法:
-- [constraint ] foreign key 字段名1 [,字段名2,...]
-- references 主键列1 [, 主键列2, ...]
create table tb_dept1(
id int(11) primary key,
name varchar(22) not null,
location varchar(50)
);
create table tb_emp5(
id int(11) primary key,
name varchar(25),
dept_id int(11),
salary float,
constraint fk_emp_dept1 foreign key(dept_id) references tb_dept1(id)
);
-- 提示:
-- 子表的外键必须关联父表的主键,且关联字段的数据类型必须匹配
非空约束 not null
唯一约束
唯一约束:列的值唯一,允许为空,但是空值也只能有一个
作用:确保一列或者多列不出现重复值
语法:
-- 1. 在定义完列之后直接指定唯一约束:
-- 字段名 数据类型 unique
create table tb_dept2(
id int(11) primary key,
name varchar(22) unique,
location varchar(50)
);
-- 2. 在定义完所有列之后指定唯一约束
-- [constraint ] unique()
-- e.g.
create table tb_dept3(
id int(11) primary key,
name varchar(22),
location varchar(50),
constraint cons_dept3_name unique(name)
);
默认约束 default
自增 auto_increment
一个表只能有一个字段使用 auto_increment 约束,且改字段必须为主键的一部分,可以是任何整数类型
语法
-- 字段名 数据类型 auto_increment
create table tb_emp8(
id int(11) primary key auto_increment,
name varchar(25) not null,
dept_id int(11),
salary float
);