数据库SQL语句练习一
mysql约束条件
非空约束 | not null |
---|---|
唯一性约束 | unique |
主键约束 | primary key |
外键约束 | foreign key |
日期字段说明
类型 | 字节 | 格式 | 用途 | 是否支持设置默认值 |
---|---|---|---|---|
date | 3 | YYYY-MM-DD | 日期 | 否 |
time | 3 | HH:MM:SS | 时间值 | 否 |
year | 1 | YYYY | 年份 | 否 |
datetime | 8 | YYYY-MM-DD HH:MM:SS | 日期和时间 | 否 |
timestamp | 4 | YYYYMMDD HHMMSS | 日期和时间,可作时间戳 | 是 |
timestamp
current_timestamp | on update current_timestamp |
---|---|
插入当前系统的时间 | 当执行update时,并且字段有 on update current_timestamp属性。则字段无论值有没有变化,它的值也会跟着更新为当前update操作时的时间。 |
-
创建一个 school 数据库,数据库的字符编码使用 utf8
create database school default charset utf8;
-
在 school 数据库中,创建一个 student 表,表的存储类型为 innodb,表的结构如下:
create table student( sid int(10)UNSIGNED primary key not null, name varchar(10) not null, gender varchar(1) not null, age int(3) not null, birthday date not null, phone char, class int unsigned not null, grade int unsigned not null )
-
查看创建得student表状态
desc student
-
在 school 数据库中,创建一个 class 表,表的存储类型为 innodb,表的结构如下:
create table class( cid int unsigned primary key not null auto_increment, name varchar(10) not null, tid int unsigned not null, size int UNSIGNED not null DEFAULT 0, location VARCHAR(30) not null )
-
查看创建得class表状态
desc class
-
在school 数据库中,创建一个 teacher 表,表的存储类型为 innodb,表的结构如下:
create table teacher( tid int unsigned primary key not null auto_increment, name varchar(10) not null, age int unsigned not null, education enum('本科','硕士','博士')not null, hiredate timestamp not null default current_timestamp )
-
使用 SQL 语句为以上三个表中的字段添加外键约束。
### student.class是外键(student关联class表);class.tid是外键(class表关联teacher表) alter table student add foreign key(class) references class (tid) alter table class add foreign key(tid) references teacher (tid)
查看三表:
desc student
desc class
desc teacher
-
使用 SQL 语句为以上三个表中的字段添加 CHECK 约束
(1) 学生姓名、班级姓名和教师姓名不得超过10个字符 alter table student add check (name<11) alter table class add check (name<11) alter table teacher add check (name<11) (2) 学生的年龄必须在 19-30 岁之间。 alter table student add check(age in (19 30)) (3) 手机号码的长度必须达到 11 位 alter table student add check(phone=11)