目录

  • 一、简介/入门
    • 1.1 安装
    • 1.2 简介:
    • 1.3 MySQL数据
    • 1.4着重号的使用
    • 1.5 SQL查询常量、表达式、函数
    • 1.6 给查询的结果起别名
    • 1.7 +加号的作用
    • 1.8 concat() 拼接字符串
    • 1.9 处理null,IFNULL
    • 1.10 mysql服务的启动
  • 二、登入数据库、选中表、查看表信息
    • 2.1 登入退出
    • 2.2 查询数据库服务器中有哪些数据库
    • 2.3 选中某个数据库 (use database_name;)
    • 2.4 显示指定数据库下的所有表
    • 2.5 显示表的属性(features,attributes)信息
    • 2.6 显示数据表的详细索引信息
    • 2.7 查看表格结构
    • 2.8 查看表格里的所有样本
    • 2.9 查看数据库中所有表的状态
    • 2.10 查看当前所在哪个database
    • 2.11 查看当前MySQL是什么版本
  • 三、创建数据库和表
    • 3.1 创建数据库
    • 3.2 创建数据表
    • 3.3 添加数据记录/样本
    • 3.4 创建表约束
  • 六、普通查询数据
    • 6.1 查询单个列/属性
    • 6.2 查询指定的多个列/属性 ,或所有列
    • 6.3 查询指定某列样本返回的是集合(set)/去重
    • 6.4 查询满足指定条件下的样本记录 where
      • 6.4.1 条件运算符举例
      • 6.4.2 逻辑运算符案例
      • 6.4.3 Between and
      • 6.4.4 使用in查询某个属性的多个值
    • 6.5 查询样本时按照指定的顺序进行排序 order by
    • 6.6 查询满足某个条件的样本的个数 统计(count)
    • 6.7 查询表中某个属性最大值的样本
    • 6.8 查询样本时限制返回的数目 #num1可省,默认从0起始位置开始
    • 6.9 指定模式查询样本 like
      • 6.9.1 案例
    • 6.10 查询某类分组样本的平均数
    • 6.11 分组按照条件查询 (group by 后面要跟条件用的是having不是where)
    • 6.12 查询某属性是空值/非空的样本 is null/ is not null
    • 查询工号为176的员工的姓名和部门号和年薪
  • 七、函数查询
    • 1.字符函数
      • 1.length()
      • 2.concat() 拼接
      • 3.upper(),lower() 大小写
      • 4.substr() 截取字符串
      • 5.instr() 查字符串的子串第一次出现的索引值
      • 6.trim() 去除前后空格/指定字符
      • 7.lpad() 左填充字符
      • 8. rpad() 右填充字符
      • 9.replace()替换
    • 2.数学函数
      • 1.round()四舍五入
      • 2.cell() 向上取整
      • 3.floor()向下取整
      • 4. truncate(x,y) 截断
      • 5.mod()取余数
    • 3.日期函数
      • 1.now()显示当前日期和时间
      • 2.curdate() 显示当前日期,不包含时间
      • 3.curtime() 显示当前时间,不包含日期
      • 4.获取指定时间的年、月、日、小时、分钟、秒
      • 5. str_to_date() 将日期格式的字符转换成指定格式的日期
      • 6.date_format() 将日期转换成字符
      • 7.datediff()查询相差时间 (P58)
    • 4.其他函数
      • 1.version()
      • 2.database()
    • 5.流程控制函数 (P50)
      • 1.if函数
      • 2. case函数,多条件判断
    • 6. 函数例题
      • 1.显示当前的时间
      • 2.查询employee_id,last_name,salary,以及工资提高20%的new salary
      • 3. 将员工的姓名按首字母排序,并写出名字长度
      • 4.做一个查询显示如下结果
      • 5. 如下查询
    • 6. 统计函数、聚合函数、分组函数 (P53)
      • 1. 求和、平均值、最小值、最大值,计数
      • 2.特点
      • 3.可以和distinct搭配 (P55)
      • 4. count()详细描述
      • 5. 分组函数使用注意事项
  • 八、分组查询group by (59)
    • 1.语法
    • 2. having 分组后的筛选
    • 3.多属性分组
    • 4.案例
    • 4.分组查询特点
  • 九、连接查询/多表查询
    • 1.按功能分类连接查询
    • 2. 内连接【92语法】(略看,主要还是99语法)
      • 1.等值连接,两个表的交集部分
      • 2.非等值连接
      • 3.自连接
    • 3.内连接【99语法】
      • 1.等值连接
      • 2.非等值连接(比大小)
      • 3.自连接
    • 4. 外连接
      • 1.左右连接
      • 2.全外连接 mysql不支持
      • 3.交叉连接
      • 4.总结外连接
      • 5.案例讲解
  • 十、子查询
    • 1.分类
    • 2.where/having 后面的子查询
      • 1.标量子查询(单行子查询)
      • 2.列子查询(多行子查询)
      • 3.行子查询(一行多列)
      • 4.放在select后面的子查询
    • 3.from 后面的子查询
    • 4.exists后面的子查询(也叫相关子查询)
    • 5.案例
  • A.数据类型附表
    • 1.数值类型
    • 2.日期和时间类型
    • 3.字符串类型
    • 4.数值型如何设置正负符号
    • 5.浮点型,定点型
    • 6.字符串类型
    • 7.枚举enum()
    • 8.集合set()
    • 9.时间datetime,timestamp

一、简介/入门

1.1 安装

安装向导:https://www.runoob.com/mysql/mysql-install.html 此电脑MySQL账户名cjr
安装带有管理器的版本https://dev.mysql.com/downloads/installer/

https://www.runoob.com/w3cnote/windows10-mysql-installer.html

1.2 简介:

数据库的好处:
1.可以持久化存储数据到本地
2.结构化查询

DB:Database,存储数据的仓库,保存了一系列有组织的数据

DBMS:Database Management System 数据库管理系统,数据库是通过DBMS创建和操作的

常见DBMSL: MySQL,Oracle,DB2(适合海量数据),SqlServer(只能安装在windows下)

SQL:Structured Query Language,结构化查询语言,专门用来与数据库通信的语言

优点:

1.3 MySQL数据

存储在我的坚果云中的Mysql文件夹中

1.4着重号的使用

feature_name
`` 数字1左边的那个键就是着重号,如果一个属性名称跟系统自带的字段相同,可加着重号做区分

1.5 SQL查询常量、表达式、函数

select 100;
select 'john';
select version();

1.6 给查询的结果起别名

起别名的好处

  1. 便于理解
  2. 如果查询的字段有重名,可以用别名区别开来

起别名的方式

  1. 用 as
  2. 用空格
select 100 as 结果;
select version() as 版本;
select 'john' 名字; #直接空格隔开

select salary as 薪水 from employees;

1.7 +加号的作用

在MySql中 + 号只有一个作用:运算符

  1. 两个变量都是数值型,做加法运算
select 60+80;

return 140

  1. 两个变量其中一个是数值型,另一个是字符串格式的数值,就会试图将字符型的数字转换成数值型
select '100'+20;

return 120

  1. 如果字符型变量无法转换成数值型,那么就把他变成0
select 'john' + 20;

return 20

  1. 只要其中一个变量为null,结果都会为null
select null + 20;

return null

1.8 concat() 拼接字符串

select concat('a','b','c');

return abc

例子:

select first_name,last_name,concat(first_name,' ',last_name) as full_name from employees;

1.9 处理null,IFNULL

如果某一列中有很多null,如果跟其他列用concat合并,返回的只会是null。要用ifnull来处理``

ifnull(feature_name,value) 如果feature_name是null,返回设置的value值

例子:

select concat(first_name,',',last_name,',', ifnull(commission_pct,0)) as out_put from employees;

1.10 mysql服务的启动

方式一:通过命令行:cmd net start 服务名 net stop 服务名
方式二:计算机–右键–管理–服务

二、登入数据库、选中表、查看表信息

2.1 登入退出

本机登录

# mysql -uusername -ppassword
mysql -uroot -pcjrxxxxxxx

联机

mysql -h主机名 -P端口号 -u用户民 -p密码
#退出
exit;

2.2 查询数据库服务器中有哪些数据库

show databases;  #先看有哪些数据库

2.3 选中某个数据库 (use database_name;)

#选择要操作的Mysql数据库,使用该命令后所有Mysql命令都只针对该数据库
use cjrtest;

2.4 显示指定数据库下的所有表

#显示指定数据库的所有表
show tables from database_name;

#显示当前数据库下的所有表
show tables;

2.5 显示表的属性(features,attributes)信息

#显示数据表的属性,属性类型,主键信息 是否为 NULL,默认值等其他信息。
show columns from cjrtest;

2.6 显示数据表的详细索引信息

show index from table_name;

2.7 查看表格结构

跟show columns from table_name; 几乎一样

describe table_name;

2.8 查看表格里的所有样本

select * from table_name;

2.9 查看数据库中所有表的状态

show table status from database_name;show table status from database_name like 'country%'; #查询表格名称以country开头的表的信息show table status from database_name like 'country%'\G;  # 加上 \G,查询结果按列打印



2.10 查看当前所在哪个database

select database();

2.11 查看当前MySQL是什么版本

select version();


第二种方法:
还没登陆mysql时,在cmd输入mysql --version

三、创建数据库和表

3.1 创建数据库

create database database_name;

3.2 创建数据表

CREATE TABLE table_name(feature_name1 type,feature_name2 type,feature_name3 type,.............);

例1:

CREATE TABLE pet(name VARCHAR(20),owner VARCHAR(20),species VARCHAR(20),sex CHAR(1),birth DATE,death DATE);

例2:有设置默认值

create table cjrtest(
id int primary key auto_increment,
name varchar(10) not null default '',
gender char(1) not null default '',
company varchar(20) not null default '',
salary decimal(8,2) not null default 0.00,
meal smallint not null default 0)

3.3 添加数据记录/样本

insert into table_name
(feature1,feature2,feature3,feature4..)
values
(value1,value2,value3,value4…)

例子:

insert into cjrtest
(id,name,gender,company,salary,meal) #可省略,也可选择特定的属性
values
(1,'cjr','男','Alibaba',16000.00,2000),
(2,'lsq','女','Baidu',15000,213),
(3,'zjm','女','Pupu',14000,321),
(4,'Ld','男','Aoda',9210,321),
(5,'Sa','男','Jingdong',8321,231),
(6,'Jin','女','Meituan',3012,398);

3.4 创建表约束

六、普通查询数据

6.1 查询单个列/属性

select column_name from table_name;

6.2 查询指定的多个列/属性 ,或所有列

select column_name1,column_name2... from table_name;
# 查询所有列
select * from table_name;

6.3 查询指定某列样本返回的是集合(set)/去重

只能加一个属性

select distinct column_name from table_name;

例子:查询employees表格中部门编号,去重的

select distinct department_id from employees;

6.4 查询满足指定条件下的样本记录 where

select */column_name,... from table_name where feature operator value;

此处operator是运算符:

  1. 条件运算符:=、>=、<=、<、>;不等于的符号!=或<>;

  2. 逻辑运算符:and、or、not 对应的符号: &&、 ||、 !

  3. 模糊查询:

  • between:在某个范围内 (between x and y);
  • like:搜索某种模式
  • in: 指定值在某个集合里 (in (200,300,400)) in类似于=,但可指定多个值

6.4.1 条件运算符举例

  1. 查询工资大于12000的员工信息 ,属性:salary, 表格employees
select * from employees where salary > 12000;

  1. 查询 部门编号不等于90的员工名和部门编号
select concat(first_name,' ',last_name) as full_name, department_id from employees where department_id !=90;

6.4.2 逻辑运算符案例

and or not 逻辑运算符的作用就是用来连接条件运算符

  1. 查询工资在10000到20000之间的员工名、工资、奖金
select concat(first_name,' ',last_name) as full_name,salary,commission_pct
from employees
where salary>10000 and salary<20000;


2. 查询部门编号不在90-110之间,或工资高于15000的员工信息

select *
from employees
where not (department_id >=90 and department_id <=100) or salary >15000;

6.4.3 Between and

查询部门编号在90-120之间的样本 [90,120]包含90,120临界值; 90<=x<=120

select *
from employees
where department_id between 90 and 120;

6.4.4 使用in查询某个属性的多个值

查询工作名(job_id)称为’IT_PROG’或’FI_MGR’ 的样本

select * from employees where job_id in ('IT_PROG','FI_MGR');#等于
select * from employees where job_id='IT_PROG' or job_id='FI_MGR';

6.5 查询样本时按照指定的顺序进行排序 order by

order by 字句一般放在查询语句的最后,limit字句除外

select */column_name from table_name order by column_name ASC/DESC;# ORDER BY 多列的时候,先按照第一个column name排序,在按照第二个column name排序;
select */column_name from table_name order by column_name ASC/DESC,column_name ASC/DESC;

desc 或者 asc 只对它紧跟着的第一个列名有效

案例:
1.对表达式/别名进行排序, 表达式(计算公式:月薪推导出年薪)
按年薪降序,查询employees表,月薪salary,年终奖金率commission_pct

select *,salary*12*(1+ifnull(commission_pct,0)) as 年薪 from employees
order by 年薪 desc;

2.对函数值进行排序
按姓名的长度进行排序 last_name

select length(last_name) 名字长度, last_name, salary
from employees
order by 名字长度;

6.6 查询满足某个条件的样本的个数 统计(count)

select count(*) from table_name where feature operator value;

6.7 查询表中某个属性最大值的样本

select */columns from table_name where feature=(select max(feature) from table_name);
select stu_id,course_id from score where score=(select max(score) from score);#拆成2步
#1.从score表中找到最高分: select max(score) from score
#2.查询最高分的 stu_id 和 course_id  将上面找到的最高分赋值给
select stu_id,course_id from score where score=最高分

6.8 查询样本时限制返回的数目 #num1可省,默认从0起始位置开始

select */columns from table_name limit num1,num2; #num1:起始位置;num2:查询样本的数目

6.9 指定模式查询样本 like

select */columns from table_name where feature like pattern;

例子:

select * from table_name where name like '%r';  # 查询name属性下以r为结尾的样本
select * from table_name where name like 'C%';  # 查询name属性下以C为开头的样本
select * from table_name where name like '%jin%'; #查询name属性下包含jin字段的样本
select * from table_name where name not like '%jin%'; #查询name属性下包不含jin字段的样本
select * from table_name where name like '_jr'; #查询name属性下任意1个字符开头+'jr'的样本
select * from table_name where website like 'G_o_le';  #查询类似Google的样本
select * from table_name where website like 'G_o_l%'

6.9.1 案例

1.查询员工中包含字符a的员工信息

select * from employees where last_name like '%a%';

2.查询第二个字符是下划线的员工信息,下划线本身就是通配符要用\转义

select * from employees where last_name like '_\_%';

推荐用es cape 转义,用escape定义转义的字符

select * from employees where last_name like '_$_%' escape '$';

6.10 查询某类分组样本的平均数

select avg(feature) from table_name where feature operator value;

6.11 分组按照条件查询 (group by 后面要跟条件用的是having不是where)

select feature2,avg(feature1) from table_name group by feature2;

6.12 查询某属性是空值/非空的样本 is null/ is not null

不能用 = null 来找

select last_name,commission_pct from employees where commission_pct is null;
select last_name,commission_pct from employees where commission_pct is not null;


安全等于 <=> 也可判断null值

查询工号为176的员工的姓名和部门号和年薪

last_name, first_name, department_id,salary(月薪), commission_pct(年薪比率,有null值)

select concat(last_name,first_name) as full_name,department_id,salary*(1+ifnull(commission_pct,0))*12 as 年薪
from employees
whereid =176;

七、函数查询

1.字符函数

1.length()

length() 量字符串的字节个数 !!!不是字符个数!!!

select length('张三丰hahaha');

返回15,因为在utf8编码格式下,一个中文占3个字节,一个英文字母占1个字节
jbk编码格式,中文占2个

2.concat() 拼接

select concat(last_name,'_','first_name') as 姓名 from employees;

3.upper(),lower() 大小写

select upper('john');
select lower('CHEN');
select concat(upper(last_name),'_',upper(first_name)) as 姓名 from employees;

4.substr() 截取字符串

substring 的缩写
SQL语法中,初始值是1而不是0

select substr('李莫愁爱上了陆展元',7) as out_put;

返回:陆展元

#截取从指定索引处指定长度的字符,这里的3指的是长度,不是截止点
select substr('李莫愁爱上了陆展元',1,3) as out_put;

返回:李莫愁

案例:last_name首字母大写,其他小写

select concat(upper(substr(last_name,1,1)),lower(substr(last_name,2))) from employees;

5.instr() 查字符串的子串第一次出现的索引值

注意是第一次出现的位置!如果找不到返回0

select instr('I love you.','love') as out_put;

返回3

6.trim() 去除前后空格/指定字符

select trim('    love    ') as out_put;
select trim('a' from 'aaaaaa love aaaa') as out_put;

7.lpad() 左填充字符

指定填充字符串,填充到指定的长度

select LPAD('love',10,'*') as out_put;

返回:******love

如果指定的长度,小于原本的字符串长度,会被截断

select LPAD('love',2,'*') as out_put;

返回lo

8. rpad() 右填充字符

select RPAD('love',2,'*') as out_put;

9.replace()替换

select replace('I love love love you.','love','like') as out_put;

返回I like like like you.

2.数学函数

1.round()四舍五入

select round(1.65); # 返回:2
select round(1.653,2); # 返回: 1.65 保留两位小数
select round(-1.65); #返回: -2

2.cell() 向上取整

返回>=该参数的最小整数

select cell(1.52); # 返回:2
select cell(1.00); # 返回:1
select cell(-1.00); #返回:-1

3.floor()向下取整

返回<=该参数的最大整数

select floor(-9.1); #返回:-10
select floor(9.99); #返回:9

4. truncate(x,y) 截断

select truncate(1.6999,2); #返回1.69 ,截断至2位小数

5.mod()取余数

mod(a,b) = a-a/b*b

select mod(10,3); #返回:1
select mod(-10,-3); #返回:-1

3.日期函数

1.now()显示当前日期和时间

select now();

2020-09-18 21:46:03

2.curdate() 显示当前日期,不包含时间

currentdate

select curdate();

3.curtime() 显示当前时间,不包含日期

select curtime();

4.获取指定时间的年、月、日、小时、分钟、秒

select year(now()) as 年;
select year('1998-01-01') as 年;
select year(hiredate) as 年 from employees;
select month(now()) as 月; #9
select monthname(now()) as 月;                #September
day
hour
minute
second

5. str_to_date() 将日期格式的字符转换成指定格式的日期

select str_to_date('9-13-1999','%m-%d-%Y'); #1999-09-13

select * from employees
where hiredate = str_to_date('4-3 1992','%c-%d %Y');

6.date_format() 将日期转换成字符

select date_format('1995/2/14','%Y年%m月%d日');

例子:查询有奖金的员工名和入职日期(xx月/xx日 xx年)

select last_name,date_format(hiredate,'%Y年-%m月-%d日') from employees
where commission_pct is not null;

7.datediff()查询相差时间 (P58)

select datediff('2017-9-12','2017-10-1');

案例:
查询hiredate最大值和最小值相差多少天

select datediff(max(hiredate),min(hiredate)) from employees;

4.其他函数

1.version()

查询数据库版本号

select version();

2.database()

查询当前所在的数据库

select database();

show databases;要区分开

5.流程控制函数 (P50)

reference

1.if函数

select if(判别式,如果为真的值,如果为假的值);
select if(10>5,'大','小');
select last_name,if(commission_pct is null,'没奖金','有奖金') as 有无奖金 from employees;

2. case函数,多条件判断

案例1:
department_id=30,则显示salary1.1
department_id=40,则显示salary
1.2
department_id=50,则显示salary*1.3
department_id为其他,则salary显示不变

select salary as 原始工资,department_id,
case department_id    #注意这里加了要判断的字段
when 30 then salary*1.1
when 40 then salary*1.2
when 50 then salary*1.3
else salary
end as 新工资
from employees;

案例2:
查询员工的工资情况
如果工资>20000,显示A级
如果工资>15000,显示B级
如果工资>10000,显示C级
否则显示D级

select salary,
case   #注意这里没有字段
when salary>20000 then 'A级'
when salary>15000 then 'B级'
when salary>10000 then 'C级'
else 'D级'
end as 工资级别
from employees;

6. 函数例题

1.显示当前的时间

select now()

2.查询employee_id,last_name,salary,以及工资提高20%的new salary

select employee_id,last_name,salary,salary*1.2 as 'new salary'
from employees;

3. 将员工的姓名按首字母排序,并写出名字长度

select last_name,substr(last_name,1,1) as first_item,length(last_name) as name_length
from employees
order by first_item asc;

4.做一个查询显示如下结果

select concat(last_name,' earns ',salary,' monthly but wants ',salary*3) as 'dream salary'
from employees;

5. 如下查询

select job_id as job,
case job_id
when 'AD_PRES' then 'A'
when 'ST_MAN' then 'B'
when 'IT_PROG' then 'C'
when 'SA_REP' then 'D'
when 'ST_CLERK' then 'E'
end as grade
from employees;

6. 统计函数、聚合函数、分组函数 (P53)

1. 求和、平均值、最小值、最大值,计数

select sum(salary) from employees;
select avg(salary) from employees;
select round(avg(salary),2) from employees; #保留两位
select min(salary) from employees;
select max(salary) from employees;
select count(salary) from employees;

2.特点

1.sum(),avg() 只用于处理数值型数据
2.max(),min(),count()可以处理任何类型,数值、字符、日期
3.以上分组函数都忽略null值,求平均时分母不包含null,最大最小值不计null,count()计数本身就统计非空的值

3.可以和distinct搭配 (P55)

#去重

select sum(distinct salary) from employees;
select avg(distinct salary) from employees;
....

4. count()详细描述

#通常用来统计行数,一行中只要有一个属性不为空就统计上
select count(*) from employees;
#相当于新增了一列都是1的列,统计1的个数,等于统计行数。数字无所谓多少,都是常量值
select count(1) from employees;

5. 分组函数使用注意事项

不能分组函数(统计函数)跟调用属性同时
以下做法是错的!!!!!!!!!

select avg(salary),employee_id from employees;

八、分组查询group by (59)

1.语法

select 分组函数,列名(必须要出现在group by之后)
from 表名
[where 筛选条件]
group by 要分组统计的列名
[order by 字句]

2. having 分组后的筛选

select 分组函数,列名(必须要出现在group by之后)
from 表名
[where 筛选条件]
group by 要分组统计的列名
[having 筛选条件]
[order by 字句]

3.多属性分组

查询每个部门每个工种的员工平均工资

select avg(salary),department_id,job_id from employees
group by department_id,job_id;

4.案例

1.查询每个部门的平均工资

select department_id,avg(salary) from employees group by department_id;

2.查询每个工种job_id的最高工资

select job_id,max(salary) from employees group by job_id;

3.从departments表中查询每个位置location_id有多少个样本

select count(*),location_id from departments group by location_id;

4.查询邮箱中包含a字符的,每个部门department_id的平均工资

select avg(salary),department_id from employees
where email like '%a%'
group by department_id;

5.查询有奖金的每个领导manager_id手下员工的最高工资

select max(salary),manager_id from employees
where commission_pct is not null
group by manager_id;


6.查询哪个部门的员工个数大于2
第一步:查询每个部门的员工个数
第二步:每个部门的员工个数大于2

select count(*) as 员工个数,department_id from employees
group by department_id
having count(*)>2;

7.查询每个工种,有奖金的员工的最高工资,且最高工资大于12000的工种编号和最高工资

select job_id,max(salary) from employees
where commission_pct is not null
group by job_id
having max(salary)>12000;

8.查询领导编号>102的每个领导手下的最低工资>5000的领导编号是哪个,以及其最低工资

select manager_id,min(salary) from employees
where manager_id>102
group by manager_id
having min(salary)>5000;

9.按员工姓名的长度进行分组,查询每一组员工个数,筛选员工个数>5的有哪些

select length(last_name),count(*) from employees
group by length(last_name)
having count(*)>5;

10.查询各个job_id的员工工资的最大值,最小值,平均值,总和,并按job_id升序

select job_id,max(salary),min(salary),avg(salary),sum(salary) from employees
group by job_id
order by job_id asc;

11.查询最高工资和最低工资的差距

select max(salary)-min(salary) as difference from employees;

12.查询各个管理者手下的最低工资,最低工资不能低于6000,没有管理者的员工不计算在内

select min(salary),manager_id from employees
where manager_id is not null
group by manager_id
having min(salary)>=6000;

4.分组查询特点

九、连接查询/多表查询

要查询的字段/属性来自多个表就要用到连接查询

如果没有用连接条件,只是用如下语句进行查询,只会产生笛卡儿集的错误情况

select column1,column2 from table1,table2;

实际要用where连接,查询beauty表中与boys表中是一对情侣的名字

select Name,boyName from beauty,boys
where beauty.boyfriend_id = boys.id;

1.按功能分类连接查询

1.内连接:

  • 等值连接
  • 非等值连接
  • 自连接

2.外连接:

  • 左外连接
  • 右外连接
  • 全外连接

3.交叉连接

2. 内连接【92语法】(略看,主要还是99语法)

1.等值连接,两个表的交集部分

案例1:查询女神名所对应的男神名

select Name,boyName  #字段名
from beauty,boys     #表名
where beauty.boyfriend_id = boys.id;  #查询条件     

案例2:查询员工名对应的部门名

select last_name,department_name
from employees,departments
where employees.department_id = departments.department_id;

案例3:查询员last_name,job_id,job_title,从两个表employees,jobs查询,
两个表中都有job_id属性,作为连接条件

select last_name,employees.job_id,job_title
from employees,jobs
where employees.job_id = jobs.job_id;

起别名,提高简洁度,避免歧义产生ambiguous错误

select last_name,e.job_id,job_title
from employees as e,jobs as j
where e.job_id = j.job_id;

案例4:加筛选条件,查询有奖金的员工名last_name,部门名department_name,奖金commission_pct

#用and 连接筛选条件和 连接条件select last_name,department_name,commission_pct
from employees,departments
where commission_pct is not null
and employees.department_id = departments.department_id;

案例5:查询城市名中第二个字符为o的部门名和城市名
从departments表和locations表找

select department_name,city
from departments,locations
where departments.location_id=locations.location_id
and city like '_o%';

案例6:结合分组,查询每个城市的部门个数

select count(*) as 部门个数,city
from departments,locations
where departments.location_id = locations.location_id
group by city;

案例7:查询有奖金的每个部门的部门名称和部门领导编号,和该部门的最低工资

select department_name,departments.manager_id,min(salary),commission_pct
from departments,employees
where commission_pct is not null
and departments.department_id = employees.department_id
group by department_name,departments.manager_id;

案例8:查询每个工种的工种名和员工个数,并按员工个数降序

select job_title,count(*)
from employees,jobs
where employees.job_id = jobs.job_id
group by jobs.job_title
order by count(*) desc;

案例9:三表连接
查询员工名、部门名和所在的城市

select last_name,department_name,city
from employees,departments,locations
where employees.department_id = departments.department_id
and departments.location_id = locations.location_id;

案例10:查询90号部门员工的job_id和90号部门的location_id

select job_id,d.location_id
from employees as e,departments as d
where e.department_id = d.department_id
and e.department_id=90;

案例11:选择city在Toronto工作的员工的
last_name,job_id,department_id,department_name

select last_name,job_id,e.department_id,department_name
from employees e,departments d,locations l
where e.department_id = d.department_id
and d.location_id = l.location_id
and city='Toronto';

案例12:查询每个工种、每个部门的部门名、工种名、和最低工资

select min(salary),job_title,department_name
from jobs j,employees e,departments d
where e.job_id = j.job_id
and e.department_id = d.department_id
group by e.job_id,e.department_id;

案例13:查询每个国家下的部门个数大于2的国家编号

select country_id,count(*)
from locations l,departments d
where l.location_id = d.location_id
group by country_id
having count(*)>2;

2.非等值连接

案例1:查询员工的工资和工资级别(从job_grades表查)

select salary,grade_level
from employees,job_grades
where salary between job_grades.lowest_sal and job_grades.highest_sal;

3.自连接

查询员工名及id和他上级的名称和id

select e.employee_id,e.last_name,m.employee_id,m.last_name as 主管名
from employees as e,employees as m
where e.manager_id = m.employee_id;

案例:

select e.last_name as employees, e.employee_id as Emp ,
m.last_name as manager, m.employee_id as'Mgr#'
from employees e,employees m
where e.manager_id = m.employee_id;

3.内连接【99语法】

select 属性列表
from 表1 【别名】 【连接类型关键字inner、left、right、full,cross】
join 表2 【别名】
on 连接条件  #表1的x属性连接表2的y属性
【where 筛选条件】
【group by 分组】
【having 分组后筛选条件】
【order by 排序列表】

1.等值连接

案例1:查询员工名、部门名

select last_name,department_name
from employees e
inner join departments d
on e.department_id = d.department_id;

案例2:查询员工名包含e的员工名、工种名

select last_name,job_title
from employees e
inner join jobs j
on e.job_id = j.job_id
where last_name like '%e%';

案例3:查询部门个数>3的城市名和部门个数

 select city,count(*) 部门个数
from locations l
inner join departments d
on l.location_id = d.location_id
group by city #注意是按城市分组,而不是部门分组
having count(*) >3;

2.非等值连接(比大小)

案例1:查询员工的工资级别,从job_grades表中查

select grade_level,salary
from job_grades j
inner join employees e
on e.salary between lowest_sal and highest_sal; # e.salary > lowest_sal and e.salary < highest_sal

案例2:查询工资级别,且该级别下员工数大于20的个数,按工资级别降序

select grade_level,salary,count(*)
from job_grades j
inner join employees e
on e.salary between lowest_sal and highest_sal
group by grade_level
having count(*)>20
order by grade_level desc;

3.自连接

查询 员工的名字和上级的名字

select e.last_name,m.last_name
from employees e
inner join employees m
on e.manager_id = m.employee_id;

4. 外连接

外连接的查询结果为主表中的所有记录
如果从表中没有和主表匹配的,则显示null
如果从表中有和它匹配的,则显示匹配的值
外连接查询结果= 内连接结果+主表中有而从表中没有的记录

1.左右连接

查询女生表beauty中没有男朋友的样本(boys表)

use girls;
select beauty.*,boyName
from beauty
left join boys
on beauty.boyfriend_id = boys.id
where boys.id is null;

案例:查询哪个部门是没有员工的 ,所有的部门都存在departments表里

select department_name,e.employee_id
from departments d
left join employees e
on d.department_id = e.department_id
where e.employee_id is null;

2.全外连接 mysql不支持

全连接的结果= 内连接的结果+表1中有但表2没有的+表2中有但表1没有的

select beauty.*,boys.*
from beauty
full join boys
on beauty.boyfriend_id = boys.id;

3.交叉连接

等于笛卡尔乘积的结果

use girls;
select g.*,b.*
from beauty g
cross join boys b;

4.总结外连接

5.案例讲解

1.查询编号>3的女神的id,名字及男朋友信息,如果有则列出详细信息,如果没有,则null

select beauty.id,name,boys.*
from beauty
left join boys
on beauty.boyfriend_id = boys.id
where beauty.id>3;

2.查询哪个城市没有部门

select city,department_name
from locations l
left join departments d
on l.location_id = d.location_id
where d.department_id is null;

3.查询部门名为SAL或IT的员工信息,没有的用null填充

select e.* #注意使用as改写后,select也必须要用改写后的名称,要不然找不到
from departments d
left join employees e
on d.department_id = e.department_id
where d.department_name = 'SAL' or d.department_name = 'IT'; #或者用in d.department_name in ('SAL','IT')

十、子查询

出现在其他语句中的select语句,称为子查询或内查询
外部的查询语句称为主查询或外查询
子查询的执行优先于主查询,主查询用到了子查询的结果

示例:

select last_name from employees
where department in (select department_id from departmentswhere location_id=1700);

1.分类

按照子查询出现的位置划分:

  • select 后面:仅支持标量子查询
  • from 后面:支持表子查询
  • where 或 having 后面:支持标量/列/行子查询
  • exists 后面:支持表子查询

按结果集分类

  • 标量子查询(结果集是一行一列,其实就是一个数值)
  • 列子查询(一列多行)
  • 行子查询(一行多列)
  • 表子查询(结果集一般为多行多列)

2.where/having 后面的子查询

1.标量子查询(单行子查询)

案例1:谁的工资比Abel高?

select last_name,salary
from employees
where salary>(select salary from employees where last_name = 'Abel');

案例2:返回job_id 与141号员工相同,salary比143号员工多的员工姓名,job_id,工资

select last_name, job_id, salary
from employees
where job_id = (select job_idfrom employeeswhere employee_id=141)
and salary>(select salaryfrom employeeswhere employee_id=143);

案例3:返回公司工资最少的员工的last_name,job_id,salary

select last_name,job_id,salary
from employees
where salary = (select min(salary)from employees);

案例4:查询最低工资大于50号部门最低工资的部门id和其最低工资

select department_id,min(salary)
from employees
group by department_id
having min(salary)>(select min(salary)from employeeswhere department_id=50); 

2.列子查询(多行子查询)

一般搭配着多行操作符

any,all可以用min,max代替;要根据大于号小于号来灵活判断

案例1:返回location_id是1400或1700的部门中的所有员工姓名

select last_name
from employees
where department_id in (select distinct department_id #最好去重from departments where location_id in (1400,1700)
);

案例2:返回其他工种比job_id为’IT_PROG’的工种任一工资低的员工的员工号,姓名,job_id,salary

分解1:查询job_id = 'IT_PROG’部门的任一工资

select salary
from employees
where job_id = 'IT_PROG'

分解2:查询员工号,姓名,job_id,salary,salary<any(分解1的结果)

select last_name,employee_id,job_id,salary
from employees
where salary<any(select salaryfrom employeeswhere job_id = 'IT_PROG'
) and job_id<>'IT_PROG';

any转换成max

select last_name,employee_id,job_id,salary
from employees
where job_id <> 'IT_PROG'
and salary  < (select max(salary) from employees where job_id = 'IT_PROG');

3.行子查询(一行多列)

案例:查询员工编号最小并且工资最高的员工信息

select * from employees
where employee_id = (select min(employee_id)from employees)
and salary = (select max(salary)from employees);

而行子查询语法,只有一样的操作符(>,=,<)时才可用

select * from employees
where (employee_id,salary) = (select min(employee_id),max(salary)from employees);

4.放在select后面的子查询

案例:查询每个部门的部门信息和员工个数

select d.*,(select count(*) from employees ewhere e.department_id = d.department_id) as 员工个数
from departments d;

案例2:查询员工号=102的部门名
连接查询就可以做出来,但试着用子查询

select (select department_namefrom departments dinner join employees eon d.department_id = e.department_idwhere employee_id=102);

3.from 后面的子查询

注意起别名
案例:查询每个部门的平均工资的工资等级
分解1:查询每个部门的平均工资和id

select avg(salary),department_id
from employees
group by department_id

分解2:把查到的平均工资换成等级,要把上面得到的表重命名进行连接

select avg_sal.*,grade_level
from (select avg(salary) as a,department_idfrom employeesgroup by department_id
) as avg_sal
inner join job_grades
on avg_sal.a between lowest_sal and highest_sal;

4.exists后面的子查询(也叫相关子查询)

exists()只判断有没有值存在,有值就是1,没有值就是0
exists可以用in或其他的查询语句代替
exists子查询实现执行外查询在执行exists内的子查询,顺序跟之前的子查询相反
案例1:查询有员工的部门名

select department_name
from departments d
where exists(select * from employees ewhere d.department_id = e.department_id);
select department_name
from departments d
where d.department_id in(select department_idfrom employees);

5.案例

1.查询和Zlotkey相同部门的员工和工资

select salary,last_name,department_id
from employees
where department_id = (select department_idfrom employeeswhere last_name = 'Zlotkey');

2.查询工资比公司平均工资高的员工的employee_id,last_name,salary

select employee_id,last_name,salary
from employees
where salary >(select avg(salary)from employees);

3.查询各部门中工资比本部门的平均工资高的员工的employee_id,last_name,salary

select employee_id,last_name,salary
from(select avg(salary) avg_sal,department_idfrom employeesgroup by department_id) as a
inner join employees e
on e.department_id = a.department_id
where e.salary>a.avg_sal;

4.查询和姓名中包含字母u的员工在相同部门的员工的employee_id,last_name

select employee_id,last_name
from employees
where department_id in ( select distinct department_idfrom employeeswhere last_name like '%u%');

5.查询在部门的location_id,为1700的部门工作的员工的员工号

select employee_id
from employees
where department_id in (select distinct department_idfrom departmentswhere location_id=1700) ;

6.查询管理者是K_ing的员工姓名和工资

select last_name,salary,manager_id
from employees
where manager_id in (select employee_idfrom employeeswhere last_name = 'K_ing');

7.查询工资最高的员工的姓名,要求first_name,last_name显示在一列,列名为姓名

select concat(first_name,' ',last_name) as 姓名
from employees
where salary = (select max(salary)from employees);

A.数据类型附表

MySQL中定义数据字段的类型对你数据库的优化是非常重要的。

MySQL支持多种类型,大致可以分为三类:数值、日期/时间和字符串(字符)类型。

1.数值类型

包括严格数值数据类型(INTEGER、SMALLINT、DECIMAL和NUMERIC),
以及近似数值数据类型(FLOAT、REAL和DOUBLE PRECISION)。

2.日期和时间类型

表示时间值的日期和时间类型为DATETIME、DATE、TIMESTAMP、TIME和YEAR。
每个时间类型有一个有效值范围和一个"零"值,当指定不合法的MySQL不能表示的值时使用"零"值。
TIMESTAMP类型有专有的自动更新特性,将在后面描述。

3.字符串类型


注意:char(n) 和 varchar(n) 中括号中 n 代表字符的个数,并不代表字节个数,比如 CHAR(30) 就可以存储 30 个字符。
CHAR 和 VARCHAR 类型类似,但它们保存和检索的方式不同。它们的最大长度和是否尾部空格被保留等方面也不同。在存储或检索过程中不进行大小写转换。
BINARY 和 VARBINARY 类似于 CHAR 和 VARCHAR,不同的是它们包含二进制字符串而不要非二进制字符串。也就是说,它们包含字节字符串而不是字符字符串。这说明它们没有字符集,并且排序和比较基于列值字节的数值值。
BLOB 是一个二进制大对象,可以容纳可变数量的数据。有 4 种 BLOB 类型:TINYBLOB、BLOB、MEDIUMBLOB 和 LONGBLOB。它们区别在于可容纳存储范围不同。

有 4 种 TEXT 类型:TINYTEXT、TEXT、MEDIUMTEXT 和 LONGTEXT。对应的这 4 种 BLOB 类型,可存储的最大长度不同,可根据实际情况选择。

4.数值型如何设置正负符号

create table sign_test (t1 int unsigned, #无符号,只有正数t2 int
);

如果不设置unsigned,默认是有正负符号的
如果插入的数值超出了规定类型的临界值,会报异常,并且会插入最接近的临界值。
数值型类型可以不用设置长度,有默认长度,自己设置也行。

添加zerofill会把不够设置长度的部分用0填充,一旦设置zerofill就默认为该列是无符号的,只有正数

create table sign_test (t1 int(7) zerofill unsigned, #无符号,只有正数t2 int(7) zerofill
);insert into sign_test values
(123,123)

5.浮点型,定点型

M:代表小数位数+整数位数之和
D:代表小数位数
如果超出范围,则返回临界值。

float 和double
浮点型:

float(M,D)
double(M,D)

定点型:

decimal(M,D)
create table test_float (f1 float(5,2), #插入五个数字,小数位2位f2 double(5,2),f3 decimal(5,2)
);insert into test_float values (1234.52,1234.52,2145.12) #插入的值都是999.99
  • float 和double 通常可以不加M和D,他是根据你插入的值来调整自身精度
  • decimal必须加(M,D),默认是(10,0)十位整数,不含小数
  • 定点型精度较高
  • 一般用float,节省空间

选数值型时的原则:越简单越好!越节省空间越好

6.字符串类型

M:最大的字符数,一个字母是一个字符,一个汉字也是一个字符
char(M):比较耗费资源 ,但效率略高。适用于性别这种只有男/女的定长字符
varchar(M):耗费资源少,但效率略低。姓名,长度变化较大

7.枚举enum()

create table test_enum (c1 enum('a','b','c')
);insert into test_enum values
('a'),
('b'),
('c'),
('A');


不能插入不在enum()列表里的值,可以用在存储性别这类数据

8.集合set()

create table test_set(s1 set('a','b','c','d')
);insert into test_set values
('a'),
('A,B'),
('a','c','d');select * from test_set;

9.时间datetime,timestamp

timestamp会根据服务器所在的时区进行调整,timestamp占的空间小

MySQL1【个人学习笔记】相关推荐

  1. Hadoop学习笔记—18.Sqoop框架学习

    Hadoop学习笔记-18.Sqoop框架学习 一.Sqoop基础:连接关系型数据库与Hadoop的桥梁 1.1 Sqoop的基本概念 Hadoop正成为企业用于大数据分析的最热门选择,但想将你的数据 ...

  2. 七、DevOps学习笔记

    DevOps学习笔记(第七节 docker数据持久化) 2.1 数据持久化之Data Volume 数据卷 VOLUME 1.创建一个mysql的容器docker run -d -v mysql:/v ...

  3. PyTorch 学习笔记(六):PyTorch hook 和关于 PyTorch backward 过程的理解 call

    您的位置 首页 PyTorch 学习笔记系列 PyTorch 学习笔记(六):PyTorch hook 和关于 PyTorch backward 过程的理解 发布: 2017年8月4日 7,195阅读 ...

  4. 容器云原生DevOps学习笔记——第三期:从零搭建CI/CD系统标准化交付流程

    暑期实习期间,所在的技术中台-效能研发团队规划设计并结合公司开源协同实现符合DevOps理念的研发工具平台,实现研发过程自动化.标准化: 实习期间对DevOps的理解一直懵懵懂懂,最近观看了阿里专家带 ...

  5. 容器云原生DevOps学习笔记——第二期:如何快速高质量的应用容器化迁移

    暑期实习期间,所在的技术中台-效能研发团队规划设计并结合公司开源协同实现符合DevOps理念的研发工具平台,实现研发过程自动化.标准化: 实习期间对DevOps的理解一直懵懵懂懂,最近观看了阿里专家带 ...

  6. 2020年Yann Lecun深度学习笔记(下)

    2020年Yann Lecun深度学习笔记(下)

  7. 2020年Yann Lecun深度学习笔记(上)

    2020年Yann Lecun深度学习笔记(上)

  8. 知识图谱学习笔记(1)

    知识图谱学习笔记第一部分,包含RDF介绍,以及Jena RDF API使用 知识图谱的基石:RDF RDF(Resource Description Framework),即资源描述框架,其本质是一个 ...

  9. 计算机基础知识第十讲,计算机文化基础(第十讲)学习笔记

    计算机文化基础(第十讲)学习笔记 采样和量化PictureElement Pixel(像素)(链接: 采样的实质就是要用多少点(这个点我们叫像素)来描述一张图像,比如,一幅420x570的图像,就表示 ...

  10. Go 学习推荐 —(Go by example 中文版、Go 构建 Web 应用、Go 学习笔记、Golang常见错误、Go 语言四十二章经、Go 语言高级编程)

    Go by example 中文版 Go 构建 Web 应用 Go 学习笔记:无痕 Go 标准库中文文档 Golang开发新手常犯的50个错误 50 Shades of Go: Traps, Gotc ...

最新文章

  1. php判断数组不重复的元素,php从数组中随机选择若干不重复元素
  2. 言论丨马库斯回应14大质疑,重申深度学习怀疑论
  3. BetaBot 木马分析
  4. Python 基础整理(未完)
  5. android adb打开gps,adb 命令行模拟GPS位置信息
  6. codeblock生成64位dll_Pythonnet/clr : Unable to find assembly xxxx.dll
  7. Spring vs Seam
  8. 几个经常需要自定义的View总结
  9. 搭建Redis服务器
  10. POJ3208-Apocalypse Someday【数位dp】
  11. 计算机教师专业发展论文,关于教师专业发展的计算机专业论文
  12. 2016 年 ACM/ICPC 青岛区域赛 Problem C Pocky
  13. copy a random link
  14. Diverse Team(CF-988A)
  15. RR调度(Round-robin scheduling)简单介绍
  16. c#数据库事务锁类型
  17. 大数据Hadoop学习(一)入门
  18. 高等数学:第一章 函数与极限(6)极限存在准则、两个重要极限
  19. 九大背包问题专题--完全背包问题(详解,最优解)
  20. 研究表明:手机移动数据可用于预测犯罪行为

热门文章

  1. java之JVM学习全过程学习记录
  2. 参加ScrumMaster认证(CSM)心得
  3. C语言:Unix时间戳-转-UTC时间
  4. 华南农业大学操作系统课设(模拟磁盘文件系统实现)(JavaFX)(单人课设)
  5. STC15W4K系列单片机读取DHT11温湿度数据发送到串口
  6. 爬虫-selenium(二)微博账号登录淘宝
  7. 数据可视化分析教学课件——FineBI实验册节选====交通运输及物流管理等专业
  8. 《云计算》-安全策略-扫描与抓包分析-使用NMAP扫描回去指定主机/网段的相关信息、使用tcpdump分析FTP访问中的明文交换信息
  9. QQ机器人协议平台停运原因分析以及未来走势
  10. 一星级挑战:08 数字加密