1.定义(分类)
在了解 SQL 之前我们需要知道下面这几个概念
- 数据定义语言: 简称DDL (Data Definition Language),用来定义数据库对象:数据库、表、列等;
- 数据操作语言: 简称DML (Data Manipulation Language),用来对数据库中表的记录进行更新。关键字: insert、update、delete等
- 数据控制语言: 简称DCL(Data Control Language),用来定义数据库访问权限和安全级别,创建用户等。关键字: grant等
- 数据查询语言: 简称DQL(Data Query Language),用来查询数据库中表的记录,关键字: select from where等
2.CRUD入门
表的创建(DDL)
数据类型:
创建表:
auto_increment代表自增
约束:
删除表:
表的插入,更新,删除(DML)
插入表
更新表
删除表
表的查询(DQL)
基本的查询
distinct代表不重复
条件查询
运算符:
实现
-- 1.查询 username为 wzz 的人员信息:
select * from user where username='wzz';
-- 2.查询 age大于等于10的人员信息:
select * from user where age>=10;
-- 3.查询 signature是null的人员信息:
select * from user where signature is null;
-- 4.查询 signature不是null的人员信息:
select * from user where signature is not null;
-- 5.查询 commentTime是在对应时间段间的人员信息:
select * from comment where commentTime >= '2022-5-18 23:58:41' and commentTime <= '2022-5-21 23:58:41';
-- 6.查询 id是1,commentTime是在对应时间段间的人员信息:
select * from comment where commentTime <= '2022-5-18 23:58:41' and authorID = 1;
-- 7.查询 or的数据:
select * from user where age = 8 or age =20;
select * from user where age in (8,20);
-- 8.查询 模糊查询:
select * from user where username like '%杨%';
-- 9.查询 模糊查询2个字符的username:
select * from user where username like '__'
聚合函数
分组查询
排序查询
分页查询
if,when表达式
mysql进阶
连表
一对多
表的创建
-- auto-generated definition
create table tb_staff
(
id int auto_increment comment '组件id'
primary key,
username varchar(20) not null comment '用户名',
password varchar(30) not null comment '密码',
name varchar(10) not null comment 'name',
gendar tinyint unsigned not null comment '性别,1男,2女人
',
image varchar(300) null comment '图片
',
job tinyint unsigned null comment '工作
',
entrydate date null comment '入职日期
',
createtime datetime null comment '创建时间',
endtime datetime null comment '结束时间',
deptid int unsigned null comment '部门id
',
constraint tb_staff_username_uindex
unique (username)
);
-- auto-generated definition
create table tb_dept
(
id int auto_increment
primary key,
name varchar(10) not null,
createtime datetime not null,
endtime datetime not null,
constraint table_dept_tname_uindex
unique (name)
)
comment '部门表
';
外键
alter table tb_staff drop foreign key tb_staff_tb_dept_id_fk;
alter table tb_staff
add constraint tb_staff_tb_dept1_id_fk
foreign key (deptid) references tb_dept (id);
一对一
多对多
多表查询
select * from tb_staff,tb_dept where tb_staff.deptid = tb_dept.id;
内连接
外连接
子查询
查询name=未来的信息表
select * from tb_staff where deptid = (select id from tb_dept where name='未来');
行子查询:
表子查询
事务
概念
![6KB0}LR{4Y]
R7(~~LJWH.png
使用
四大特性
索引
概念
优缺点
语法
图片来源:B站黑马程序员,javaweb视频