首页 > 数据库 >MySQL基础

MySQL基础

时间:2023-05-25 21:57:03浏览次数:49  
标签:name -- 基础 dept emp MySQL id select

1 MySQL简介

视频链接:黑马程序员 MySQL数据库

MySQL是一种开源的关系型数据库管理系统(RDBMS),由瑞典的MySQL AB公司开发。MySQL是目前最流行的关系型数据库之一,广泛应用于Web应用程序、企业级应用和大数据处理等领域。

MySQL支持多用户同时访问同一个数据库实例,并提供了可扩展性和高可用性的解决方案。它使用SQL语言进行数据操作和管理,具有灵活的数据模型、强大的查询功能和安全可靠的特性。

MySQL支持多种操作系统,包括Windows、Linux和macOS等。此外,MySQL还提供了多种客户端工具,如MySQL Workbench、Navicat等,方便用户进行数据库管理和开发。

MySQL的主要特点包括:

  • 开源免费:MySQL是开源软件,可以免费使用和分发。
  • 跨平台支持:MySQL可以在多种操作系统上运行,包括Windows、Linux和macOS等。
  • 可扩展性:MySQL可以通过添加更多的服务器节点来实现水平扩展,从而提高性能和可靠性。
  • 安全性:MySQL提供了多种安全机制,如加密、权限控制和审计等,保护数据的机密性和完整性。
  • 高性能:MySQL具有高效的查询引擎和索引机制,可以快速地检索和处理大量数据。
  • 支持多种存储引擎:MySQL支持多种不同的存储引擎,如InnoDB、MyISAM等,可以根据不同的应用场景选择合适的存储引擎。

SQL语句分类

  1. DDL(Data Definition Language):定义数据结构的语言。DDL用于创建、修改和删除数据库、表、视图、索引等基本对象。
  2. DML(Data Manipulation Language):用于操纵数据的语言。DML用于对数据库中的数据进行插入、更新、删除等操作。
  3. DQL(Data Query Language):查询语言,用于检索数据库中的数据。DQL可以执行SELECT语句,从表中检索特定的数据行。
  4. DCL(Data Control Language):控制数据的语言。DCL用于管理数据库中的权限和安全设置。

2 SQL语法

2.1 SQL通用语法

  1. SQL语句可以单行或多行书写,以分号结尾。
  2. SQL语句可以使用空格/缩进来增强语句的可读性。
  3. MySQL数据库的SQL语句 不区分大小写,关键字建议使用大写。
  4. 注释:
    单行注释:-- 注释内容 或 # 注释内容(MySQL特有)
    多行注释:/*注释内容*/

2.2 SQL常用数据类型

SQL MS Access、MySQL 和 SQL Server 数据类型 | 菜鸟教程 (runoob.com))

2.3 DDL(定义数据库)

1 数据库操作

查询所有数据库

SHOW DATABASES;

查询当前数据库

SELECT DATABASE();

创建

CREATE DATABASE (数据库名Database_Name);  
create database if not exists (数据库名);
create database Database_Name default charset utf8mb4; -- 定义了字符集

删除

DROP DATABASE Database_Name;  
DROP DATABASE if exists Database_Name;  

使用

use Database_Name;  

2 表操作

查询当前数据库所有表

SHOW TABLES;

查询表结构

DESC 表名;

查询指定表的建表语法

SHOW CREATE TABLE 表名;

创建表

CREATE TABLE 表名(
	字段1 字段1类型 COMMENT '字段1注释',
    字段2 字段2类型 COMMENT '字段2注释',
    字段3 字段3类型 COMMENT '字段3注释'
) COMMENT '表注释';

-- 例如:
CREATE TABLE tb_user(
	id int COMMENT '编号',
    name varchar(50) COMMENT '姓名',
    age int COMMENT '年龄',
    gender varchar(2) COMMENT '性别'
) COMMENT '表注释';

删除表

drop table [if exist] 表名;

删除指定表,并重新创建该表(相当于格式化表)

truncate table 表名;

修改表名

alter table 表名 rename to 新表名;

增加字段

alter table 表名 add 字段名 类型(长度) comment 'XX';

修改数据类型

alter table 表名 modify 字段名 新数据类型(长度);

修改字段名和字段类型

alter table 表名 change 旧字段名 新字段名 类型(长度) comment 'XX';

删除字段

alter table 表名 drop 字段名;

2.4 DML(表中数据增删改)

给指定字段添加数据

INSERT INTO table_name (column1, column2, column3....)  
VALUES (value1, value2, value3.....);

给全部字段添加数据

INSERT INTO table_name  
VALUES (value1, value2, value3....); 

批量添加数据

INSERT INTO table_name (column1, column2, column3, ...) 
VALUES (value1, value2, value3, ....), (value1, value2, value3, ....);

-- 或者给全部字段
INSERT INTO table_name 
VALUES (value1, value2, value3, ....), (value1, value2, value3, ....);

修改数据

UPDATE table_name SET [column_name1 = value1, ... column_nameN = valueN] [WHERE condition];

删除数据

DELETE FROM table_name [WHERE condition];  

2.5 DQL(表中数据查询)

查询语法

  • 执行顺序:FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT
  • 编写顺序:
SELECT
    字段列表
FROM
    表名字段
WHERE
    条件列表
GROUP BY
    分组字段列表
HAVING
    分组后的条件列表
ORDER BY
    排序字段列表
LIMIT
    分页参数

基本查询

-- 查询指定字段
select 字段1, 字段2, 字段3 from 表名;

-- 查询所有字段
select * from 表名;

-- 设置别名
select 字段1 as 别名1, 字段2 as 别名2, 字段3 as 别名3 from 表名;

select workaddress as '工作地址' from emp;

-- 去除重复记录
select distinct 字段 from emp;

条件查询

select 字段1, 字段2, 字段3 from 表名 where 条件列表;

运算符

比较运算符 功能
> 大于
>= 大于等于
< 小于
<= 小于等于
= 等于
<> 或 != 不等于
BETWEEN … AND … 在某个范围内(含最小、最大值)
IN(…) 在in之后的列表中的值,多选一
LIKE 占位符 模糊匹配(_匹配单个字符,%匹配任意个字符)
IS NULL 是NULL
逻辑运算符 功能
AND 或 && 并且(多个条件同时成立)
OR 或 或者(多个条件任意一个成立)
NOT 或 ! 非,不是

使用样例

-- 4. 查询没有身份证号的员工信息
select * from emp where idcard is NULL;

-- 5. 查询有身份证号的员工信息
select * from emp where idcard is not NULL;

-- 7. 查询年龄在15岁(包含)到20岁(包含)直接的员工信息
select * from emp where age between 15 and 20;  -- 必须先最小值and最大值
select * from emp where age >= 15 and age <= 20;
select * from emp where age >= 15 && age <= 20;

-- 9. 查询年龄等于18 或 20 或 40 的员工信息
select * from emp where age = 18 or age = 20 or age = 40;
select * from emp where age in(18,20,40);

-- 10. 查询姓名为两个字的员工信息
select * from emp where name like '__';

-- 11. 查询身份证号最后一位是X的员工信息
select * from emp where idcard like '_________________X';
select * from emp where idcard like '%X';

聚合函数

函数 功能
count 统计数量
max 最大值
min 最小值
avg 平均值
sum 求和

语法

SELECT 聚合函数(字段列表) FROM 表名;
SELECT count(id) from employee where workaddress = "广东省";

使用样例

-- 聚合函数
-- 1. 统计该企业员工数量
select count(id) from emp;
select count(*) from emp;

-- 2. 统计该企业员工的平均年龄
select avg(age) from emp;

-- 3. 统计该企业员工的最大年龄
select max(age) from emp;

-- 4. 统计该企业员工的最小年龄
select min(age) from emp;

-- 5. 统计西安地区员工的年龄之和
select sum(age) from emp where workaddress = '西安';

分组查询

  • 通常配合聚合来操作
SELECT 字段列表 [字段后可直接加别名] FROM 表名 [ WHERE 条件 ] GROUP BY 分组字段名 [ HAVING 分组后的过滤条件 ];

where 和 having 的区别

  • 执行时机不同:where是分组之前进行过滤,不满足where条件不参与分组;having是分组后对结果进行过滤。
  • 判断条件不同:where不能对聚合函数进行判断,而having可以。

使用样例

-- 分组查询
-- 1. 根据性别分组,统计男性员工 和 女性员工的数量
select gender, count(*) '数量' from emp group by gender;

-- 2. 根据性别分组,统计男性员工 和 女性员工的平均年龄
select  gender, avg(age) '平均年龄' from emp group by gender;

-- 3. 查询年龄小于45的员工,并根据工作地址分组,获取员工数量大于等于3的工作地址
select workaddress, count(*) from emp where age < 45 group by workaddress having count(*) >= 3;
select workaddress, count(*) from emp where age < 45 group by workaddress having count(*) >= 3;
select workaddress, count(*) as adress_count from emp where age < 45 group by workaddress having adress_count >= 3;

注意事项

  • 执行顺序:where > 聚合函数 > having
  • 分组之后,查询的字段一般为聚合函数分组字段,查询其他字段无任何意义

排序查询

SELECT 字段列表 FROM 表名 ORDER BY 字段1 排序方式1, 字段2 排序方式2;

排序方式

  • ASC: 升序(默认)
  • DESC: 降序

注意事项

如果是多字段排序,当第一个字段值相同时,才会根据第二个字段进行排序

使用样例

-- 排序查询
-- 1. 年龄升序
select * from emp order by age ASC;
select * from emp order by age;  -- 升序可以省略

-- 2. 入职时间降序
select * from emp order by entrydate DESC;

-- 3. 年龄升序,年龄相同,入职时间降序
select * from emp order by age asc, entrydate desc;

分页查询

SELECT 字段列表 FROM 表名 LIMIT 起始索引, 查询记录数;

注意事项

  • 起始索引从0开始,起始索引 = (查询页码 - 1) * 每页显示记录数
  • 分页查询是数据库的方言,不同数据库有不同实现,MySQL是LIMIT
  • 如果查询的是第一页数据,起始索引可以省略,直接简写 LIMIT 10

使用样例

-- 分页查询
-- 1. 查询第1页员工数据,每页展示10条记录
select * from emp limit 10;
select * from emp limit 0,10;

-- 2. 查询第2页员工数据,每页展示10条记录---起始索引=(查询页码 - 1)*每页显示记录数, 查询记录数
select * from emp limit 10, 10;

2.6 DCL(创建数据库用户和权限)

查询用户

USER mysql;
SELECT * FROM user;

创建用户

CREATE USER '用户名'@'主机名' IDENTIFIED BY '密码';  -- 只能访问当前主机
CREATE USER '用户名'@'%' IDENTIFIED BY '密码';  -- 可以访问任意主机

修改用户密码

ALTER USER '用户名'@'主机名' IDENTIFIED WITH mysql_native_password BY '新密码';

删除用户

DROP USER '用户名'@'主机名';

使用样例

-- 创建用户itcast,只能在当前主机localhost访问,密码123456
create user 'itcast'@'localhost' identified by '123456';

-- 创建用户heima,能在任意主机访问,密码123456
create user 'heima'@'%' identified by '123456';

-- 修改heima密码1234
alter user 'heima'@'%' identified with mysql_native_password by '1234';

-- 删除用户itcast@localhost
drop user 'itcast'@'localhost';

注意事项

  • 主机名可以使用 % 通配

权限控制

常用权限:

权限 说明
ALL, ALL PRIVILEGES 所有权限
SELECT 查询数据
INSERT 插入数据
UPDATE 修改数据
DELETE 删除数据
ALTER 修改表
DROP 删除数据库/表/视图
CREATE 创建数据库/表

查询权限 show grants

SHOW GRANTS FOR '用户名'@'主机名';

授予权限 grant

GRANT 权限列表 ON 数据库名.表名 TO '用户名'@'主机名';

撤销权限 revoke

REVOKE 权限列表 ON 数据库名.表名 FROM '用户名'@'主机名';

例子

-- 查询权限
show grants for 'heima'@'%';

-- 授予权限 (授予针对于itcase这个数据库的所有表的所有权限)
grant all on itcase.* to 'heima'@'%';

-- 查询权限 (撤销针对于itcase这个数据库的所有表的所有权限)
revoke all on itcase.* from 'heima'@'%';

注意事项

  • 多个权限用逗号分隔
  • 授权时,数据库名和表名可以用 * 进行通配,代表所有

3 函数

3.1 字符串函数

常用函数

函数 功能
CONCAT(s1, s2, …, sn) 字符串拼接,将s1, s2, …, sn拼接成一个字符串
LOWER(str) 将字符串全部转为小写
UPPER(str) 将字符串全部转为大写
LPAD(str, n, pad) 左填充,用字符串pad对str的左边进行填充,达到n个字符串长度
RPAD(str, n, pad) 右填充,用字符串pad对str的右边进行填充,达到n个字符串长度
TRIM(str) 去掉字符串头部和尾部的空格
SUBSTRING(str, start, len) 返回从字符串str从start位置起的len个长度的字符串

使用样例

-- 拼接 CONCAT(s1, s2, …, sn)
select concat('Hello',' MySQL');

-- 小写 LOWER(str)
select lower('I AM SPIDERMAN');

-- 大写 UPPER(str)
select upper('i am spiderman');

-- 左填充 LPAD(str, n, pad)
select lpad('hellomysql', 20, 0);

-- 右填充 RPAD(str, n, pad)
select rpad('hellomysql', 20, 0);

-- 去除空格 TRIM(str)
select trim('     do you wanna build a snowman  ');

-- 切片(起始索引为1) SUBSTRING(str, start, len)
select substring('howareuiamfinethanku', 5, 5);

-- 根据业务需求,企业员工的工号统一改为5位数,不足五位的前面用0补齐
-- workno是int类型,前面加0不会显示
UPDATE emp SET workno = lpad(workno, 5, '0');

3.2 数值函数

常见函数:

函数 功能
CEIL(x) 向上取整
FLOOR(x) 向下取整
MOD(x, y) 返回x/y的模
RAND() 返回0~1内的随机数
ROUND(x, y) 求参数x的四舍五入值,保留y位小数

使用样例

-- 数值函数

-- CEIL(x) answer=2
select ceil(1.8);

-- FLOOR(x) answer=1
select floor(1.8);

-- MOD(x, y) (取余数)
select mod(4,3);

-- RAND()
select rand();

-- ROUND(x, y) 求参数x的四舍五入值,保留y位小数 answer=2.90
select round(2.899,2);

-- 生成随机6位数
select rpad(round(rand()*1000000,0),6,0);

3.3 日期函数

常用函数:

函数 功能
CURDATE() 返回当前日期
CURTIME() 返回当前时间
NOW() 返回当前日期和时间
YEAR(date) 获取指定date的年份
MONTH(date) 获取指定date的月份
DAY(date) 获取指定date的日期
DATE_ADD(date, INTERVAL expr type) 返回一个日期/时间值加上一个时间间隔expr后的时间值
DATEDIFF(date1, date2) 返回起始时间date1和结束时间date2之间的天数

使用样例

-- CURDATE()
select curdate();

-- CURTIME()
select curtime();

-- NOW()
select now();

-- YEAR(date)-- MONTH(date)-- DAY(date)
select year(now());
select month(now());
select day(now());

-- DATE_ADD(date, INTERVAL expr type)
select date_add(now(),interval 10 day);

-- DATEDIFF(date1, date2)---date1-date2
select datediff(now(),'2000-04-01');

-- 查询所有员工的入职天数,并根据入职天数倒序排序
select name, datediff(curtime(),entrydate) as entrydays from emp order by entrydays DESC;

3.4 流程函数

常用函数:

函数 功能
IF(value, t, f) 如果value为true,则返回t,否则返回f
IFNULL(value1, value2) 如果value1不为空,返回value1,否则返回value2
CASE WHEN [ val1 ] THEN [ res1 ] … ELSE [ default ] END 如果val1为true,返回res1,… 否则返回default默认值
CASE [ expr ] WHEN [ val1 ] THEN [ res1 ] … ELSE [ default ] END 如果expr的值等于val1,返回res1,… 否则返回default默认值

使用样例

-- IF(value, t, f)--如果value为true,则返回t,否则返回f
select if(false,'ok','error');

-- IFNULL(value1, value2)--如果value1不为空,返回value1,否则返回value2
select ifnull(null,'error');
select ifnull('ok','error');


-- CASE [ expr ] WHEN [ val1 ] THEN [ res1 ] … ELSE [ default ] END
-- 如果expr的值等于val1,返回res1,… 否则返回default默认值
-- 需求:查询emp表的员工姓名和工作地址(上海/北京--->一线城市,其他--->二线城市)
select
       name,
       (case workaddress when '北京' then '一线城市' when '上海' then '一线城市' else '二线城市' end) as '工作城市'
from emp;


-- CASE WHEN [ val1 ] THEN [ res1 ] … ELSE [ default ] END
-- 如果val1为true,返回res1,… 否则返回default默认值
-- 统计班级成绩{ >=85优秀, >=60及格, else不及格 }
create table  score(
    id int comment 'ID',
    name varchar(20) comment '姓名',
    math int comment '数学',
    english int comment '英文',
    chinese int comment '语文'
) comment '学员成绩表';

insert into score(id, name, math, english, chinese)
values (1, 'Tom',67,88,95),(2,'Rose',23,66,90),(3,'Jack',56,98,76);

select
       id,
       name,
       (case when math >=85 then '优秀' when math >=60 then '及格' else '不及格'end) as math,
       (case when english >=85 then '优秀' when math >=60 then '及格' else '不及格'end) as english,
       (case when chinese >=85 then '优秀' when math >=60 then '及格' else '不及格'end) as chinese
from score;

4 约束

约束 描述 关键字
非空约束 限制该字段的数据不能为null NOT NULL
唯一约束 保证该字段的所有数据都是唯一、不重复的 UNIQUE
主键约束 主键是一行数据的唯一标识,要求非空且唯一 PRIMARY KEY
默认约束 保存数据时,如果未指定该字段的值,则采用默认值 DEFAULT
检查约束(8.0.1版本后) 保证字段值满足某一个条件 CHECK
外键约束 用来让两张图的数据之间建立连接,保证数据的一致性和完整性 FOREIGN KEY
自增 自动+1,常用于id AUTO_INCREMENT

使用样例

create table user(
    id int primary key auto_increment comment 'id主键',
    name varchar(10) not null unique comment '姓名',
    age int check ( age >= 0 && age <= 120 ) comment '年龄',
    status char(1) default '1' comment '状态',
    gender char(1) comment '性别'
) comment '用户表';

4.1 外键约束(基本不用)

添加外键关联

创建表时添加

CREATE TABLE 表名(
    字段名 字段类型,
    ...
    [CONSTRAINT] [外键名称] FOREIGN KEY(外键字段名) REFERENCES 主表(主表列名)
);

创建表后添加

ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段名) REFERENCES 主表(主表列名);
  • 外键在创建后,主表中的关联无法删除,这样保证了一致性和完整性

删除外键

ALTER TABLE 表名 DROP FOREIGN KEY 外键名;

使用样例

create table dept
(
    id   int auto_increment comment 'ID' primary key,
    name varchar(50) not null comment '部门名称'
) comment '部门表';

INSERT INTO dept (id, name)
VALUES (1, '研发部'),
       (2, '市场部'),
       (3, '财务部'),
       (4, '销售部'),
       (5, '总经办');

create table emp1
(
    id        int auto_increment comment 'ID' primary key,
    name      varchar(50) not null comment '姓名',
    age       int comment '年龄',
    job       varchar(20) comment '职位',
    salary    int comment '薪资',
    entrydate date comment '入职时间',
    managerid int comment '直属领导ID',
    dept_id   int comment '部门ID'
) comment '员工表';

INSERT INTO emp1 (id, name, age, job, salary, entrydate, managerid, dept_id)
VALUES (1, '金庸', 66, '总裁', 20000, '2000-01-01', null, 5),
       (2, '张无忌', 20, '项目经理', 12500, '2005-12-05', 1, 1),
       (3, '杨逍', 33, '开发', 8400, '2000-11-03', 2, 1),
       (4, '韦一笑', 48, '开 发', 11000, '2002-02-05', 2, 1),
       (5, '常遇春', 43, '开发', 10500, '2004-09-07', 3, 1),
       (6, '小昭', 19, '程 序员鼓励师', 6600, '2004-10-12', 2, 1);

-- 建立外键关联 ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段名) REFERENCES 主表(主表列名);
alter table emp1 add constraint fk_emp1_dept_id foreign key (dept_id) references dept(id);

-- 删除外键 ALTER TABLE 表名 DROP FOREIGN KEY 外键名;
alter table emp1 drop foreign key fk_emp1_dept_id;

删除/更新行为

行为 说明
NO ACTION 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新(与RESTRICT一致)
RESTRICT 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新(与NO ACTION一致)
CASCADE 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则也删除/更新外键在子表中的记录
SET NULL 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则设置子表中该外键值为null(要求该外键允许为null)
SET DEFAULT 父表有变更时,子表将外键设为一个默认值(Innodb不支持)
ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段) REFERENCES 主表名(主表字段名) ON UPDATE 行为 ON DELETE 行为;
alter table emp1 add constraint fk_emp1_dept_id foreign key (dept_id) references dept(id) on update CASCADE on delete CASCADE ;

5 多表查询

模糊查询:XX like

多表关系

  • 一对多(多对一)
  • 多对多
  • 一对一

一对多

案例:部门与员工
关系:一个部门对应多个员工,一个员工对应一个部门
实现:在多的一方建立外键,指向一的一方的主键

img

多对多

案例:学生与课程
关系:一个学生可以选多门课程,一门课程也可以供多个学生选修
实现:建立第三张中间表,中间表至少包含两个外键,分别关联两方主键

img

使用样例

-- 多对多 --------------------------------------------------------
create table student
(
    id   int auto_increment primary key comment '主键ID',
    name varchar(10) comment '姓名',
    no   varchar(10) comment '学号'
) comment '学生表';

insert into student
values (null, '黛绮丝', '2000100101'),
       (null, '谢逊', '2000100102'),
       (null, '殷天正', '2000100103'),
       (null, '韦一笑', '2000100104');

create table course
(
    id   int auto_increment primary key comment '主键ID',
    name varchar(10) comment '课程名称'
) comment '课程表';

insert into course
values (null, 'Java'),
       (null, 'PHP'),
       (null, 'MySQL'),
       (null, 'Hadoop');

create table student_course
(
    id        int auto_increment comment '主键' primary key,
    studentid int not null comment '学生ID',
    courseid  int not null comment '课程ID',
    constraint fk_courseid foreign key (courseid) references course (id),
    constraint fk_studentid foreign key (studentid) references student (id)
) comment '学生课程中间表';

insert into student_course
values (null, 1, 1),
       (null, 1, 2),
       (null, 1, 3),
       (null, 2, 2),
       (null, 2, 3),
       (null, 3, 4);

img

一对一

案例:用户与用户详情
关系:一对一关系,多用于单表拆分,将一张表的基础字段放在一张表中,其他详情字段放在另一张表中,以提升操作效率
实现:在任意一方加入外键,关联另外一方的主键,并且设置外键为唯一的(UNIQUE)

img

使用样例

-- 一对一 -------------------------------------------------------------------
create table tb_user
(
    id     int auto_increment primary key comment '主键ID',
    name   varchar(10) comment '姓名',
    age    int comment '年龄',
    gender char(1) comment '1: 男 , 2: 女',
    phone  char(11) comment '手机号'
) comment '用户基本信息表';


create table tb_user_edu
(
    id            int auto_increment primary key comment '主键ID',
    degree        varchar(20) comment '学历',
    major         varchar(50) comment '专业',
    primaryschool varchar(50) comment '小学',
    middleschool  varchar(50) comment '中学',
    university    varchar(50) comment '大学',
    userid        int unique comment '用户ID',
    constraint fk_userid foreign key (userid) references tb_user (id)
) comment '用户教育信息表';


insert into tb_user(id, name, age, gender, phone)
values (null, '黄渤', 45, '1', '18800001111'),
       (null, '冰冰', 35, '2', '18800002222'),
       (null, '码云', 55, '1', '18800008888'),
       (null, '李彦宏', 50, '1', '18800009999');


insert into tb_user_edu(id, degree, major, primaryschool, middleschool, university, userid)
values (null, '本科', '舞蹈', '静安区第一小学', '静安区第一中学', '北京舞蹈学院', 1),
       (null, '硕士', '表演', '朝阳区第一小学', '朝阳区第一中学', '北京电影学院', 2),
       (null, '本科', '英语', '杭州市第一小学', '杭州市第一中学', '杭州师范大学', 3),
       (null, '本科', '应用数学', '阳泉第一小学', '阳泉区第一中学', '清华大学', 4);

多表查询

合并查询(笛卡尔积,会展示所有组合结果)

table1=子表,table2=父表

select * from table1, table2;

消除无效笛卡尔积:

select * from table1, table2 where table1.table2 = table2.id;

对查询结果去重:

-- 查询拥有员工的部门ID、部门名称
select distinct e.dept_id, d.name from emp as e, dept as d where e.dept_id = d.id;

使用样例

-- 创建dept表,并插入数据
create table dept
(
    id   int auto_increment comment 'ID' primary key,
    name varchar(50) not null comment '部门名称'
) comment '部门表';

INSERT INTO dept (id, name)
VALUES (1, '研发部'),
       (2, '市场部'),
       (3, '财务部'),
       (4, '销售部'),
       (5, '总经办'),
       (6, '人事部');

-- 创建emp表,并插入数据
create table emp
(
    id        int auto_increment comment 'ID' primary key,
    name      varchar(50) not null comment '姓名',
    age       int comment '年龄',
    job       varchar(20) comment '职位',
    salary    int comment '薪资',
    entrydate date comment '入职时间',
    managerid int comment '直属领导ID',
    dept_id   int comment '部门ID'
) comment '员工表';

-- 添加外键
alter table emp
    add constraint fk_emp_dept_id foreign key (dept_id) references dept (id);

INSERT INTO emp (id, name, age, job, salary, entrydate, managerid, dept_id)
VALUES (1, '金庸', 66, '总裁', 20000, '2000-01-01', null, 5),
       (2, '张无忌', 20, '项目经理', 12500, '2005-12-05', 1, 1),
       (3, '杨逍', 33, '开发', 8400, '2000-11-03', 2, 1),
       (4, '韦一笑', 48, '开发', 11000, '2002-02-05', 2, 1),
       (5, '常遇春', 43, '开发', 10500, '2004-09-07', 3, 1),
       (6, '小昭', 19, '程序员鼓励师', 6600, '2004-10-12', 2, 1),
       (7, '灭绝', 60, '财务总监', 8500, '2002-09-12', 1, 3),
       (8, '周芷若', 19, '会计', 48000, '2006-06-02', 7, 3),
       (9, '丁敏君', 23, '出纳', 5250, '2009-05-13', 7, 3),
       (10, '赵敏', 20, '市场部总监', 12500, '2004-10-12', 1, 2),
       (11, '鹿杖客', 56, '职员', 3750, '2006-10-03', 10, 2),
       (12, '鹤笔翁', 19, '职员', 3750, '2007-05-09', 10, 2),
       (13, '方东白', 19, '职员', 5500, '2009-02-12', 10, 2),
       (14, '张三丰', 88, '销售总监', 14000, '2004-10-12', 1, 4),
       (15, '俞莲舟', 38, '销售', 4600, '2004-10-12', 14, 4),
       (16, '宋远桥', 40, '销售', 4600, '2004-10-12', 14, 4),
       (17, '陈友谅', 42, null, 2000, '2011-10-12', 1, null);
       
       
-- 合并查询(笛卡尔积,会展示所有组合结果)
select * from emp, dept;
select * from emp, dept where emp.dept_id = dept.id;

连接查询

内连接

内连接查询的是两张表交集的部分

img

隐式内连接:

SELECT 字段列表 FROM 表1, 表2 WHERE 条件 ...;

显式内连接:

SELECT 字段列表 FROM 表1 [ INNER ] JOIN 表2 ON 连接条件 ... where ...;

使用样例

-- 查询员工姓名,关联部门名称 (隐式)
SELECT emp.name, dept.name FROM emp, dept WHERE emp.dept_id = dept.id ;
SELECT e.name, d.name FROM emp e, dept d WHERE e.dept_id = d.id;
-- 如果为表起了别名,就不能再通过原表名来限定字段

-- 查询员工姓名,关联部门名称 (显式)
SELECT e.name, d.name FROM emp AS e JOIN dept AS d ON e.dept_id = d.id;

**如果为表起了别名,就不能再通过原表名来限定字段
**

外连接

左外连接

查询左表所有数据,以及两张表交集部分数据

-- 表1是左表
SELECT 字段列表 FROM 表1 LEFT [ OUTER ] JOIN 表2 ON 条件 ...;

右外连接

查询右表所有数据,以及两张表交集部分数据

-- 表1是右表
SELECT 字段列表 FROM 表1 RIGHT [ OUTER ] JOIN 表2 ON 条件 ...;

使用样例

-- 查询emp表和对应的部门信息(左外)
SELECT e.* , d.name FROM emp e LEFT JOIN dept d ON e.dept_id = d.id;

-- 查询dept表和对应的员工信息(右外)
SELECT d.* , e.* FROM dept d RIGHT OUTER JOIN emp e ON e.dept_id = d.id;

左连接可以查询到没有dept的employee,右连接可以查询到没有employee的dept

左外用的比较多

自连接

SELECT 字段列表 FROM 表A 别名A JOIN 表A 别名B ON 条件 ...;

使用样例

-- 查询员工 以及 所述领导的名字 (内连接自连接)
SELECT e1.name, e2.name FROM emp e1 JOIN emp e2 ON e1.managerid = e2.id;

-- 查询员工 以及 所述领导的名字, 如果无,也要显示 (外连接自连接)
SELECT e1.name, e2.name FROM emp e1 LEFT OUTER JOIN emp e2 ON e1.managerid = e2.id;

联合查询

把多次查询的结果合并,形成一个新的查询集

  • 字段列表数量要相同
SELECT 字段列表 FROM 表A ...
UNION [ALL]
SELECT 字段列表 FROM 表B ...

使用样例

-- 将薪资低于5000的员工 和 年龄大于50的员工 全部查询出来
SELECT * FROM emp where salary < 5000
UNION
SELECT * FROM emp where age > 50;

注意事项

  • UNION ALL 会有重复结果,UNION 不会
  • 联合查询比使用or效率高,不会使索引失效

子查询

SQL语句中嵌套SELECT语句,称谓嵌套查询,又称子查询。
子查询外部的语句可以是 INSERT / UPDATE / DELETE / SELECT 的任何一个

SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);

根据子查询结果可以分为:

  • 标量子查询(子查询结果为单个值)(数字、字符串、日期)
  • 列子查询(子查询结果为一列)
  • 行子查询(子查询结果为一行)
  • 表子查询(子查询结果为多行多列)

根据子查询位置可分为:

  • WHERE 之后
  • FROM 之后
  • SELECT 之后

标量子查询

-- 标量子查询

-- 1. 查询销售部的所有员工信息
-- step 1: 查询销售部的部门ID
SELECT id FROM dept WHERE name  = '销售部';
-- step 2: 根据ID,查询员工信息
select * from emp where dept_id = 4;
-- 一条就查询完
select * from emp where dept_id = (SELECT id FROM dept WHERE name  = '销售部');


-- 查询在‘方东白’入职之后的员工信息
select entrydate from emp where name = '方东白' ;
select * from emp where entrydate > '2009-02-12';
-- 嵌套
select * from emp where entrydate > (select entrydate from emp where name = '方东白' );

列子查询

返回的结果是一列或多行。

常用操作符:

操作符 描述
IN 在指定的集合范围内,多选一
NOT IN 不在指定的集合范围内
ANY 子查询返回列表中,有任意一个满足即可
SOME 与ANY等同,使用SOME的地方都可以使用ANY
ALL 子查询返回列表的所有值都必须满足
-- 列子查询

-- 1. 查询 "销售部" 和 "市场部" 的所有员工信息
-- step 1: 查询 "销售部" 和 "市场部" 的部门ID
select id from dept where name = '销售部' or name = '市场部';
-- step 2: 根据部门ID, 查询员工信息
select * from emp where dept_id = 2 or dept_id = 4;
-- 一条就查询完
select * from emp where dept_id in (select id from dept where name = '销售部' or name = '市场部');


-- 2. 查询比 财务部 所有人工资都高的员工信息
-- step 1: 查询所有 财务部 人员工
select id from dept where name = '财务部';
select salary from emp where dept_id = 3;
select salary from emp where dept_id = (select id from dept where name = '财务部');


-- step 2: 比 财务部 所有人工资都高的员工信息
select * from emp where salary > all ( select salary from emp where dept_id = 3 );
select * from emp where salary > all ( select salary from emp where dept_id = (select id from dept where name = '财务部') );


-- 3. 查询比研发部其中任意一人工资高的员工信息
select id from dept where name = '研发部';
select salary from emp where dept_id = ( select id from dept where name = '研发部' );
select * from emp where salary > any ( select salary from emp where dept_id = ( select id from dept where name = '研发部' ) ) ;

行子查询

返回的结果是一行(可以是多列)
常用操作符:=, <, >, IN, NOT IN

-- 行子查询
-- 1. 查询与‘张无忌’的薪资及领导相同的员工信息
select salary, managerid from emp where name = '张无忌';
select * from emp where salary = 12500 and managerid = 1;
-- 一条就查询完
select * from emp where (salary, managerid) = (12500,1);
select * from emp where (salary, managerid) = (select salary, managerid from emp where name = '张无忌');
-- 用in也可以
select * from emp where (salary, managerid) in (select salary, managerid from emp where name = '张无忌');

表子查询

返回的结果是多行多列
常用操作符:IN

-- 表子查询
-- 1. 查询与 "鹿杖客" , "宋远桥" 的职位和薪资相同的员工信息
select job, salary from emp where name = '鹿杖客' or name = '宋远桥';
select * from emp where (job,salary) in (select job, salary from emp where name = '鹿杖客' or name = '宋远桥');

-- 2. 查询入职日期是 "2006-01-01" 之后的员工信息 , 及其部门信息
-- 入职日期是 "2006-01-01" 之后的员工信息
select * from emp where entrydate > '2006-01-01';
-- 把上一步查询出来的表起别名作为新表e,后引用左外连接连接上表和部门信息
select e.*, d.id from (select * from emp where entrydate > '2006-01-01') as e left join dept as d on e.dept_id = d.id;

使用样例

-- 案例
-- 数据准备
create table salgrade
(
    grade int,
    losal int,
    hisal int
) comment '薪资等级表';

insert into salgrade values (1, 0, 3000);
insert into salgrade values (2, 3001, 5000);
insert into salgrade values (3, 5001, 8000);
insert into salgrade values (4, 8001, 10000);
insert into salgrade values (5, 10001, 15000);
insert into salgrade values (6, 15001, 20000);
insert into salgrade values (7, 20001, 25000);
insert into salgrade values (8, 25001, 30000);

-- 1. 查询员工的姓名、年龄、职位、部门信息 (隐式内连接)
select e.name, e.age, e.job, d.name from emp as e, dept as d where e.dept_id = d.id;

-- 2. 查询年龄小于30岁的员工的姓名、年龄、职位、部门信息 (显示内连接)
select e.name, e.age, e.job, d.name from emp as e, dept as d where e.dept_id = d.id and age < 30;
select e.name, e.age, e.job, d.name from emp as e inner join dept as d on e.dept_id = d.id where age < 30;

-- 3. 查询拥有员工的部门ID、部门名称
select distinct e.dept_id, d.name from emp as e, dept as d where e.dept_id = d.id;

-- 4. 查询所有年龄大于40岁的员工, 及其归属的部门名称; 如果员工没有分配部门, 也需要展示出来(左外连接)
select e.name, d.name from emp as e left join dept as d on e.dept_id = d.id where age > 40;

-- 5. 查询所有员工的工资等级
-- 表: emp , salgrade
-- 连接条件 : emp.salary >= salgrade.losal and emp.salary <= salgrade.hisal
select e.*, s.grade from emp as e, salgrade as s where e.salary >= s.losal and e.salary <= s.hisal;
-- 方式一
select e.*, s.grade, s.losal, s.hisal from emp e, salgrade s where e.salary >= s.losal and e.salary <= s.hisal;
-- 方式二
select e.*, s.grade, s.losal, s.hisal from emp e, salgrade s where e.salary between s.losal and s.hisal;

-- 6.  查询 "研发部" 所有员工的信息及 工资等级
select id from dept where name = '研发部';
select e.*, s.grade from emp e, dept d, salgrade s where e.dept_id = d.id and (e.salary between s.losal and s.hisal) and d.name = '研发部';

-- 7. 查询 "研发部" 员工的平均工资
select id from dept where name = '研发部';
select avg(e.salary) from emp e, dept d where e.dept_id = d.id and d.id = (select id from dept where name = '研发部');
select avg(e.salary) from emp e, dept d where e.dept_id = d.id and d.name = '研发部';

-- 8. 查询工资比 "灭绝" 高的员工信息
select salary from emp where name = '灭绝';
select * from emp where salary > (select salary from emp where name = '灭绝');

-- 9. 查询比平均薪资高的员工信息
select avg(salary) from emp; select * from emp where salary > (select avg(salary) from emp);

-- 10. 查询低于本部门平均工资的员工信息 (假设查2)
select avg(e1.salary) from emp e1 where e1.dept_id = 1;
select avg(e1.salary) from emp e1 where e1.dept_id = 2;
select e2.* from emp e2 where e2.salary < (select avg(e1.salary) from emp e1 where e1.dept_id = e2.dept_id);

-- 11. 查询所有的部门信息, 并统计部门的员工人数
select d.id, d.name, count(e.dept_id) as numbers from emp e, dept d where e.dept_id = d.id group by e.dept_id;
select d.id, d.name , ( select count(*) from emp e where e.dept_id = d.id ) '人数' from dept d;

-- 12. 查询所有学生的选课情况, 展示出学生名称, 学号, 课程名称
-- 表: student , course , student_course
-- 连接条件: student.id = student_course.studentid , course.id =student_course.courseid
select s.name, s.id, c.name from student s, course c, student_course sc where s.id = sc.studentid and c.id =sc.courseid;

6 事务

事务是一组操作的集合,事务会把所有操作作为一个整体一起向系统提交或撤销操作请求,即这些操作要么同时成功,要么同时失败。

-- 转账操作
-- 1. 查询张三余额
select * from account where name = '张三';

-- 2. 张三的余额减少1000
update account set money = money - 1000 where name = '张三';

程序抛出异常...
-- 3. 李四的余额增加1000
update account set money = money + 1000 where name = '李四';

-- 恢复数据
update account set money = 2000 where name = '李四' or name = '张三';

事务操作

-- 方式一
-- 查看事务提交方式
SELECT @@AUTOCOMMIT;
-- 设置事务提交方式,1为自动提交,0为手动提交,该设置只对当前会话有效
SET @@AUTOCOMMIT = 0;
-- 此时为手动提交

-- 提交事务
COMMIT;
-- 一开始没执行提交时是没有反应的,执行了提交,才会有下一步

-- 一旦出错
-- 回滚事务
ROLLBACK;

-- ====================================================

-- 方式二
set @@autocommit = 1;
-- 自动提交
select @@autocommit;
-- 转账操作
start transaction ;

-- 1. 查询张三余额
select * from account where name = '张三';

-- 2. 张三的余额减少1000
update account set money = money - 1000 where name = '张三';

程序执行报错...
-- 3. 李四的余额增加1000
update account set money = money + 1000 where name = '李四';

-- 提交事务
COMMIT;

-- 回滚事务
ROLLBACK;

成功就COMMIT

失败就ROLLBACK

四大特性ACID

  • 原子性(Atomicity):事务是不可分割的最小操作但愿,要么全部成功,要么全部失败
  • 一致性(Consistency):事务完成时,必须使所有数据都保持一致状态
  • 隔离性(Isolation):数据库系统提供的隔离机制,保证事务在不受外部并发操作影响的独立环境下运行
  • 持久性(Durability):事务一旦提交或回滚,它对数据库中的数据的改变就是永久的

并发事务问题

问题 描述
脏读 一个事务读到另一个事务还没提交的数据
不可重复读 一个事务先后读取同一条记录,但两次读取的数据不同
幻读 一个事务按照条件查询数据时,没有对应的数据行,但是再插入数据时,又发现这行数据已经存在

并发事务隔离级别:

隔离级别 脏读 不可重复读 幻读
Read uncommitted
Read committed ×
Repeatable Read(默认) × ×
Serializable × × ×
  • √表示在当前隔离级别下该问题会出现
  • Serializable 性能最低;Read uncommitted 性能最高,数据安全性最差
-- 查看事务隔离级别:
SELECT @@TRANSACTION_ISOLATION;
-- 设置事务隔离级别:
SET [ SESSION | GLOBAL ] TRANSACTION ISOLATION LEVEL {READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE };
-- SESSION 是会话级别,表示只针对当前会话有效,GLOBAL 表示对所有会话有效

标签:name,--,基础,dept,emp,MySQL,id,select
From: https://www.cnblogs.com/xiufanivan/p/17433059.html

相关文章

  • linux基础
    1、Linux用户类型      超级管理员root——所有权限      普通用户——权限有限2、shell    Shell是Linux系统的用户界面,提供了用户与内核进行交互操作的一种接口。它接收用户输入的命令并把它送入内核去执行。shell也被称为LINUX的命令解释器(comm......
  • MySQL存储引擎精简版
    存储引擎简介概念:其是存储数据,建立索引,更新查询数据等操作的技术支持,引擎是基于表的,所以又称表结构常见分类InnoDBMySQL5.5之后默认引擎特点:1.操作遵循ACID原则,支持事务2.支持行锁3,支持外键约束MyISAMMySQL早期默认引擎特点:1.不支持事务和外键约束,支持表锁......
  • mysql语言
    DQL:数据查询语言->数据select+from+whereDML:数据操作语言->数据insert、update、deleteDDL:数据定义语言->数据库对象(数据库,表,索引,触发器,存储过程,函数)createalter:修改数据库对象dropDCL:数据控制语言grant:授予用户某种权限revoke:回收授予的某种权限TCL:事物控制语言star......
  • MySQL索引高级进阶详解-玩转MySQL数据库
    前言从今天开始本系列文章就带各位小伙伴学习数据库技术。数据库技术是Java开发中必不可少的一部分知识内容。也是非常重要的技术。本系列教程由浅入深,全面讲解数据库体系。非常适合零基础的小伙伴来学习。全文大约【1957】字,不说废话,只讲可以让你学到技术、明白原理的纯干......
  • MySQL索引
    一、索引介绍1、索引是一种用于快速查询和检索数据的数据结构,其本质可以看成是一种排序好的数据结构。2、优缺点:使用索引可以大大加快数据的检索速度(大大减少检索的数据量),这也是创建索引的最主要的原因创建索引和维护索引需要耗费许多时间。索引需要使用物理文件存储,也会......
  • LINUX下定时备份MYSQL数据库SHELL脚本
    备份脚本backupMysqlData.sh#!/bin/bash#备份SQL文件的路径backupdir=/home/hdkg/mysqldata/#执行导出数据库操作mysqldump--user=root--password=password--host=localhost--port=3306dataBaseName>$backupdir/backupfile_$(date+%Y%m%d).sql#删除七天前的备份数......
  • 两个MYSQL数据同步的SHELL脚本
    #/!bin/bashHOST=127.0.0.1#ip(127.0.0.1表示本机地址)USER=root#数据库用户名PASSWORD=password#数据库密码DATABASE=pig#数据库名BACKUP_PATH=/home/hdkg/bkdata/#备份目录logfile=/home/hdkg/bklog/data.log#记录日志TABLES="testtest......
  • 使用DataX从ORACLE同步数据到MYSQL
    [前提]安装python3.7oracle版本:oracle11gmysql版本:mysql5.71.下载DataXwgethttp://datax-opensource.oss-cn-hangzhou.aliyuncs.com/datax.tar.gz2.解压DataXtar-zxvfdatax.tar.gz3.编写同步脚本进入dataXbin目录cd${HOME目录}/datax/bin 编写同步脚本vioracleToMysql.json......
  • mysql数据库部署
    推荐步骤:安装Mysql5.6.46版本设置登录Mysql密码,使用root账户登录Mysql创建自己名字数据库,查看数据库实验步骤:安装Mysql5.6.46版本设置登录Mysql密码,使用root账户登录Mysql创建自己名字数据库,查看数据库......
  • 记一次windows装docker,然后nacos连接宿主机mysql报错问题
    之前一直用linux装docker,这两天有空研究下windows上装DockerDesktop。安装步骤就不一一细说了,记录几个容易忘得地方。设置docker镜像存储位置//打包现有镜像wsl--exportdocker-desktop-data"D:\\work\\other-tools\\docker\\docker-desktop-data.tar"//注销镜像wsl--......