SQL详解
SQL简介
SQL (Structured Query Language:结构化查询语言) 是用于管理关系数据库管理系统(RDBMS)。 SQL 的范围包括数据插入、查询、更新和删除,数据库模式创建和修改,以及数据访问控制。
SQL语法
-
启动MySQL80服务:以管理员身份打开命令行提示符,执行
net start mysql80
;也可以找到MySQL80
服务,右键开启。 -
查看所有数据库:show databases;
-
切换数据库:use school;
-
查看数据库下的所有表:show tables;
-
查看函数:? functions
-
主键(PRIMARY KEY):能够唯一确定一条记录的字段。
-
外键(FOREIGN KEY):外来的主键(其他表的主键)。
-
数据类型:
~ 整数:
int / integer —> -2^31 ~2^31 - 1
tinyint / smallint / bigint
int unsigned —> 0 ~ 2^32 - 1
smallint —> -32768 ~ 32767
tynyint unsigned —> 0 ~ 255
~ 小数
decimal —> decimal(10, 2):表示小数有效数字为10位,保留两位小数。
~ 字符串
char / varchar :字符串长度固定使用char,字符串长度可变使用varchar。
longtext —> longblob(二进制对象) —> 放资源路径(URL)
~ 时间日期
date / time /datetime
timestamp
~ 布尔型
boolean:底层是tinyint(1) —> 0/1
~ 枚举型
enum —> ‘M’ / ‘F’
DDL - 数据定义语言
- 创建数据库:create database school default charset utf8mb4;
或create database school default character set utf8mb4;
- 建表:
学生表
create table `tb_student`
(
`stu_id` int unsigned not null comment '学号',
`stu_name` varchar(20) not null comment '姓名',
`stu_sex` boolean default 1 not null comment '性别',
`stu_birth` date not null comment '出生日期',
`stu_addr` varchar(255) default '' comment '籍贯',
`col_id` int unsigned not null comment '所属学院',
primary key (`stu_id`),
constraint `fk_student_col_id` foreign key (`col_id`) references `tb_college` (`col_id`)
) engine=innodb comment '学生表';
老师表
create table `tb_teacher`
(
`tea_id` int unsigned not null comment '工号',
`tea_name` varchar(20) not null comment '姓名',
`tea_title` varchar(10) default '助教' comment '职称',
`col_id` int unsigned not null comment '所属学院',
primary key (`tea_id`),
constraint `fk_teacher_col_id` foreign key (`col_id`) references `tb_college` (`col_id`)
) engine=innodb comment '老师表';
课程表
create table `tb_course`
(
`cou_id` int unsigned not null comment '编号',
`cou_name` varchar(50) not null comment '名称',
`cou_credit` int not null comment '学分',
`tea_id` int unsigned not null comment '授课老师',
primary key (`cou_id`),
constraint `fk_course_tea_id` foreign key