简介:个人学习分享,如有错误,欢迎批评指正。
前言:数据库管理系统一个重要功能就是数据查询,数据查询不应只是简单返回数据库中存储的数据,还应该根据需要对数据进行筛选以及确定数据以什么样的格式显示。 MySQL数据库使用select语句来查询数据。
语法格式:
select
[all|distinct]
<目标列的表达式1> [别名],
<目标列的表达式2> [别名]...
from <表名或视图名> [别名],<表名或视图名> [别名]...
[where<条件表达式>]
[group by <列名>
[having <条件表达式>]]
[order by <列名> [asc|desc]]
[limit <数字或者列表>];
简化版语法
select *| 列名 from 表 where 条件
数据准备
创建数据库和表:
-- 创建数据库
create database if not exists mydb2;
use mydb2;
-- 创建商品表:
create table product(
pid int primary key auto_increment, -- 商品编号
pname varchar(20) not null , -- 商品名字
price double, -- 商品价格
category_id varchar(20) -- 商品所属分类
);
添加数据:
-- 添加数据:
insert into product values(null,'海尔洗衣机',5000,'c001');
insert into product values(null,'美的冰箱',3000,'c001');
insert into product values(null,'格力空调',5000,'c001');
insert into product values(null,'九阳电饭煲',200,'c001');
insert into product values(null,'啄木鸟衬衣',300,'c002');
insert into product values(null,'恒源祥西裤',800,'c002');
insert into product values(null,'花花公子夹克',440,'c002');
insert into product values(null,'劲霸休闲裤',266,'c002');
insert into product values(null,'海澜之家卫衣',180,'c002');
insert into product values(null,'杰克琼斯运动裤',430,'c002');
insert into product values(null,'兰蔻面霜',300,'c003');
insert into product values(null,'雅诗兰黛精华水',200,'c003');
insert into product values(null,'香奈儿香水',350,'c003');
insert into product values(null,'SK-II神仙水',350,'c003');
insert into product values(null,'资生堂粉底液',180,'c003');
insert into product values(null,'老北京方便面',56,'c004');
insert into product values(null,'良品铺子海带丝',17,'c004');
insert into product values(null,'三只松鼠坚果',88,null);
1.简单查询
-- 1.查询所有的商品.
select * from product;
-- 2.查询商品名和商品价格.
select pname,price from product;
-- 3.别名查询.使用的关键字是as(as可以省略的).
-- 3.1表别名:
select * from product as p;
select * from product p;
-- select p.id,u.id from product p ,user u;
-- 3.2列别名:
select pname as pn from product;
-- 4.去掉重复值.
select distinct price from product;
-- 5.查询结果是表达式(运算查询):将所有商品的价格+10元进行显示.
select pname,price+10 as newprice from product;
2.运算符操作
2.1.简介
数据库中的表结构确立后,表中的数据代表的意义就已经确定。通过MySQL运算符进行运算,就可以获取到表结构以外的另一种数据。 例如,学生表中存在一个birth字段,这个字段表示学生的出生年份。而运用MySQL的算术运算符用当前的年份减学生出生的年份,那么得到的就是这个学生的实际年龄数据。
算术运算符 | + | 加法运算 |
- | 减法运算 | |
* | 乘法运算 | |
/ 或 DIV | 除法运算,返回商 | |
% 或 MOD | 求余运算,返回余数 | |
比较运算符 | = | 等于 |
< 和 <= | 小于和小于等于 | |
> 和 >= | 大于和大于等于 | |
<=> | 安全的等于,两个操作码均为NULL时,其所得值为1;而当一个操作码为NULL时,其所得值为0 | |
<> 或!= | 不等于 | |
IS NULL 或 ISNULL | 判断一个值是否为 NULL | |
IS NOT NULL | 判断一个值是否不为 NULL | |
LEAST | 当有两个或多个参数时,返回最小值 | |
GREATEST | 当有两个或多个参数时,返回最大值 | |
BETWEEN AND | 判断一个值是否落在两个值之间 | |
IN | 判断一个值是IN列表中的任意一个值 | |
NOT IN | 判断一个值不是IN列表中的任意一个值 | |
LIKE | 通配符匹配 | |
REGEXP | 正则表达式匹配 | |
逻辑运算符 | NOT 或者 ! | 逻辑非 |
AND 或者 && | 逻辑与 | |
OR 或者 || | 逻辑或 | |
XOR | 逻辑异或 |
2.2.代码实操
-- 算数运算符
select 6 + 2;
select 6 - 2;
select 6 * 2;
select 6 / 2;
select 6 % 2;
-- 将每件商品的价格加10
select pname,price + 10 as new_price from product;
-- 将所有商品的价格上调10%
select pname,price * 1.1 as new_price from product;
-- 查询商品名称为“海尔洗衣机”的商品所有信息:
select * from product where pname = '海尔洗衣机';
-- 查询价格为800商品
select * from product where price = 800;
-- 查询价格不是800的所有商品
select * from product where price != 800;
select * from product where price <> 800;
select * from product where not(price = 800);
-- 查询商品价格大于等于60元的所有商品信息
select * from product where price >= 60;
-- 查询商品价格在200到1000之间所有商品
select * from product where price >= 200 and price <=1000;
select * from product where price >= 200 && price <=1000;
select * from product where price between 200 and 1000;
-- 查询商品价格是200或800的所有商品
select * from product where price = 200 or price = 800;
select * from product where price = 200 || price = 800;
select * from product where price in (200,800);
-- 查询含有‘裤'字的所有商品
select * from product where pname like '%裤%';
-- 查询以'海'开头的所有商品
select * from product where pname like '海%';
-- 查询第二个字为'蔻'的所有商品
select * from product where pname like '_蔻%';
-- 查询category_id为null的商品
select * from product where category_id is null; -- 下划线匹配单个字符
-- 查询category_id不为null分类的商品
select * from product where category_id is not null;
-- 使用least求最小值
select least(10, 20, 30) as small_number; -- 10
select least(10, null, 30); -- null.如果求最小值时,有一个值为null,则不会进行比较,结果直接为null;
-- 使用greatest求最大值
select greatest(10, 20, 30) as big_number;
select greatest(10, null, 30); -- null。如果求最大值时,有一个值为null,则不会进行比较,结果直接为null;
3.排序查询
3.1.简介
如果我们需要对读取的数据进行排序,我们就可以使用 MySQL 的 order by 子句来设定你想按哪个字段哪种方式来进行排序,再返回搜索结果。
select
字段名1,字段名2,……
from 表名
order by 字段名1 [asc|desc],字段名2[asc|desc]……
特点:
1.asc代表升序,desc代表降序,如果不写默认升序
2.order by用于子句中可以支持单个字段,多个字段,表达式,函数,别名
3.order by子句,放在查询语句的最后面。LIMIT子句除外
3.2.代码实操
-- 1.使用价格排序(降序)
select * from product order by price desc;
-- 2.在价格排序(降序)的基础上,以分类排序(升序)
select * from product order by price desc,category_id asc;
-- 3.显示商品的价格(去重复),并排序(降序)
select distinct price from product order by price desc;
4.聚合查询
4.1.简介
之前我们做的查询都是横向查询,它们都是根据条件一行一行的进行判断,而使用聚合函数查询是纵向查询,它是对一列的值进行计算,然后返回一个单一的值;另外聚合函数会忽略空值。
聚合函数 | 作用 |
count() | 统计指定列不为NULL的记录行数; |
sum() | 计算指定列的数值和,如果指定列类型不是数值类型,那么计算结果为0 |
max() | 计算指定列的最大值,如果指定列是字符串类型,那么使用字符串排序运算; |
min() | 计算指定列的最小值,如果指定列是字符串类型,那么使用字符串排序运算; |
avg() | 计算指定列的平均值,如果指定列类型不是数值类型,那么计算结果为0 |
4.2.代码实操
-- 1 查询商品的总条数
select count(pid) from product;
select count(*) from product;
-- 2 查询价格大于200商品的总条数
select count(*) from product where price > 200;
-- 3 查询分类为'c001'的所有商品的总和
select sum(price) from product where category_id = 'c001';
-- 4 查询商品的最大价格
select max(price) from product;
-- 5 查询商品的最小价格
select min(price) from product;
-- 6 查询分类为'c002'所有商品的平均价格
select avg(price) from product where category_id = 'c002';
4.3.聚合查询-NULL值的处理
4.3.1.简介
1、count函数对null值的处理 如果count函数的参数为星号(*),则统计所有记录的个数。而如果参数为某字段,不统计含null值的记录个数。
2、sum和avg函数对null值的处理 这两个函数忽略null值的存在,就好象该条记录不存在一样。 3、max和min函数对null值的处理 max和min两个函数同样忽略null值的存在。
4.3.2.代码实操
-- 创建表
create table mydb2.test_null(
c1 varchar(20),
c2 int
);
-- 插入数据
insert into test_null values('aaa',3);
insert into test_null values('bbb',3);
insert into test_null values('ccc',null);
insert into test_null values('ddd',6);
-- 测试
select count(*), count(1), count(c2) from test_null;
select sum(c2),max(c2),min(c2),avg(c2) from test_null;
5.分组查询
5.1.简介
分组查询是指使用group by字句对查询信息进行分组。
格式:
select 字段1,字段2… from 表名 group by 分组字段 having 分组条件;
5.2.代码实操
-- 1 统计各个分类商品的个数
select category_id ,count(*) from product group by category_id ;
如果要进行分组的话,则SELECT子句之后,只能出现分组的字段和统计函数,其他的字段不能出现:
5.3.分组之后的条件筛选-having
5.3.1.简介
分组之后对统计结果进行筛选的话必须使用having,不能使用where
where子句用来筛选 FROM 子句中指定的操作所产生的行
group by 子句用来分组 WHERE 子句的输出。
having 子句用来从分组的结果中筛选行
格式
select 字段1,字段2… from 表名 group by 分组字段 having 分组条件;
5.3.2.代码实操
-- 2.统计各个分类商品的个数,且只显示个数大于4的信息
select category_id ,count(*) as cnt from product group by category_id having count(*) > 4 order by cnt;
6.分页查询
6.1.简介
分页查询在项目开发中常见,由于数据量很大,显示屏长度有限,因此对数据需要采取分页显示方式。例如数据共有30条,每页显示5条,第一页显示1-5条,第二页显示6-10条。
格式
-- 方式1-显示前n条
select 字段1,字段2... from 表明 limit n
-- 方式2-分页显示
select 字段1,字段2... from 表明 limit m,n
m: 整数,表示从第几条索引开始,计算方式 (当前页-1)*每页显示条数
n: 整数,表示查询多少条数据
6.2.代码实操
-- 查询product表的前5条记录
select * from product limit 5
-- 从第4条开始显示,显示5条
select * from product limit 3,5
6.3.INSERT INTO SELECT语句
简介:将一张表的数据导入到另一张表中,可以使用INSERT INTO SELECT语句 。
格式
insert into Table2(field1,field2,…) select value1,value2,… from Table1
或者:
insert into Table2 select * from Table1
要求目标表Table2必须存在
select * from product;
create table product2(
pname varchar(20),
price double
);
insert into product2(pname,price) select pname,price from product;
select *from product2;
create table product3(
category_id varchar(20),
product_count int
);
insert into product3 select category_id, count(*) from product group by category_id;
select * from product3
6.4.SELECT INTO FROM语句
简介
将一张表的数据导入到另一张表中,有两种选择 SELECT INTO 和 INSERT INTO SELECT 。
格式
SELECT vale1, value2 into Table2 from Table1
要求目标表Table2不存在,因为在插入时会自动创建表Table2,并将Table1中指定字段数据复制到Table2中。
-- SQL执行顺序:from->group by->count(pid)->select->having->order by
select
category_id ,count(*) as cnt
from
product
group by
category_id
having
count(*) > 4
order by
cnt;
7.DQL-正则化表达式
7.1.简介
正则表达式(regular expression)描述了一种字符串匹配的规则,正则表达式本身就是一个字符串,使用这个字符串来描述、用来定义匹配规则,匹配一系列符合某个句法规则的字符串。在开发中,正则表达式通常被用来检索、替换那些符合某个规则的文本。 MySQL通过REGEXP关键字支持正则表达式进行字符串匹配。
模式 | 描述 |
^ | 匹配输入字符串的开始位置。 |
$ | 匹配输入字符串的结束位置。 |
. | 匹配除 "\n" 之外的任何单个字符。 |
[...] | 字符集合。匹配所包含的任意一个字符。例如, '[abc]' 可以匹配 "plain" 中的 'a'。 |
[^...] | 负值字符集合。匹配未包含的任意字符。例如, '[^abc]' 可以匹配 "plain" 中的'p'。 |
p1|p2|p3 | 匹配 p1 或 p2 或 p3。例如,'z|food' 能匹配 "z" 或 "food"。'(z|f)ood' 则匹配 "zood" 或 "food"。 |
* | 匹配前面的子表达式零次或多次。例如,zo* 能匹配 "z" 以及 "zoo"。* 等价于{0,}。 |
+ | 匹配前面的子表达式一次或多次。例如,'zo+' 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。+ 等价于 {1,}。 |
{n} | n 是一个非负整数。匹配确定的 n 次。例如,'o{2}' 不能匹配 "Bob" 中的 'o',但是能匹配 "food" 中的两个 o。 |
{n,m} | m 和 n 均为非负整数,其中n <= m。最少匹配 n 次且最多匹配 m 次。 |
7.2.代码实操
use mydb2
-- ^ 在字符串开始处进行匹配
SELECT 'abc' REGEXP '^a'; -- 1
select * from product where pname regexp '^海';
-- $ 在字符串末尾开始匹配
SELECT 'abc' REGEXP 'a$';
SELECT 'abc' REGEXP 'c$';
-- . 匹配任意字符
SELECT 'abc' REGEXP '.b';
SELECT 'abc' REGEXP '.c';
SELECT 'abc' REGEXP 'a.';
-- [...] 匹配括号内的任意单个字符,正则表达式的任意字符是否在前边的字符串中出现
SELECT 'abc' REGEXP '[xyz]';
SELECT 'abc' REGEXP '[xaz]';
-- [^...] 注意^符合只有在[]内才是取反的意思,在别的地方都是表示开始处匹配
SELECT 'a' REGEXP '[^abc]';
SELECT 'x' REGEXP '[^abc]';
SELECT 'abc' REGEXP '[^a]';
-- a* 匹配0个或多个a,包括空字符串。 可以作为占位符使用.有没有指定字符都可以匹配到数据
SELECT 'stab' REGEXP '.ta*b';
SELECT 'stb' REGEXP '.ta*b';
SELECT '' REGEXP 'a*';
-- a+ 匹配1个或者多个a,但是不包括空字符
SELECT 'stab' REGEXP '.ta+b';
SELECT 'stb' REGEXP '.ta+b';
-- a? 匹配0个或者1个a
SELECT 'stb' REGEXP '.ta?b';
SELECT 'stab' REGEXP '.ta?b';
SELECT 'staab' REGEXP '.ta?b';
-- a1|a2 匹配a1或者a2,
SELECT 'a' REGEXP 'a|b';
SELECT 'b' REGEXP 'a|b';
SELECT 'b' REGEXP '^(a|b)'; -- 以什么开头
SELECT 'a' REGEXP '^(a|b)';
SELECT 'c' REGEXP '^(a|b)';
-- a{m} 匹配m个a
SELECT 'auuuuc' REGEXP 'au{4}c';
SELECT 'auuuuc' REGEXP 'au{3}c';
-- a{m,} 匹配m个或者更多个a
SELECT 'auuuuc' REGEXP 'au{3,}c';
SELECT 'auuuuc' REGEXP 'au{4,}c';
SELECT 'auuuuc' REGEXP 'au{5,}c';
-- a{m,n} 匹配m到n个a,包含m和n
SELECT 'auuuuc' REGEXP 'au{3,5}c';
SELECT 'auuuuc' REGEXP 'au{4,5}c';
SELECT 'auuuuc' REGEXP 'au{5,10}c';
-- (abc) abc作为一个序列匹配,不用括号括起来都是用单个字符去匹配,如果要把多个字符作为一个整体去匹配就需要用到括号,所以括号适合上面的所有情况。
SELECT 'xababy' REGEXP 'x(abab)y';
SELECT 'xababy' REGEXP 'x(ab)*y';
SELECT 'xababy' REGEXP 'x(ab){1,2}y';
8.学后练习
-- 例子1---
use mydb2
create table student(
id int,
name varchar(20),
gender varchar(20),
chinese int,
enlish int,
math int
);
alter table student change enlish english int;
insert into student(id,name,gender,chinese,english,math) values(1,'张明','男',89,78,90);
insert into student(id,name,gender,chinese,english,math) values(1,'李进','男',67,53,95);
insert into student(id,name,gender,chinese,english,math) values(1,'王五','女',87,78,77);
insert into student(id,name,gender,chinese,english,math) values(1,'李一','女',88,98,92);
insert into student(id,name,gender,chinese,english,math) values(1,'李财','男',82,84,67);
insert into student(id,name,gender,chinese,english,math) values(1,'张宝','男',55,85,45);
insert into student(id,name,gender,chinese,english,math) values(1,'黄蓉','女',75,65,30);
insert into student(id,name,gender,chinese,english,math) values(1,'黄蓉','女',75,65,30);
-- 查询表中所有学生的信息。
select * from student;
-- 查询表中所有学生的姓名和对应的英语成绩。
select name,english from student;
-- 过滤表中的重复数据。
select distinct * from student;
-- 统计每个学生的总分。
select name, (chinese+english+math) as total_score from student;
-- 在所有学生总分数上加上10分特长分。
select name, (chinese+english+math+10) as total_score from student;
-- 使用别名表示学生分数。
select name, chinese as '语文',english as '英语',math as '数学' from student;
-- 查询英语成绩大于90分的同学。
select * from student where english >90;
-- 查询总分大于200分的所有同学。
select *, (chinese+english+math) as total_score from student where (chinese+english+math)>200;
select *, (chinese+english+math) as total_score from student where total_score>200; # 错误
-- 查询英语分数在80-90之间的同学。
select * from student where english>=80 and english <=90;
select * from student where english between 80 and 90;
-- 查询英语分数不在80-90之间的同学。
select * from student where not (english>=80 and english <=90);
select * from student where english<80 || english >90;
select * from student where not (english between 80 and 90);
select * from student where english not between 80 and 90;
-- 查询数学分数为89,90,91的同学。
select * from student where math=89 or math=90 or math=91;
select * from student where math in (89,90,91);
-- 查询所有姓李的学生英语成绩。
select name,english from student where name like '李%';
-- 查询数学成绩80并且语文成绩80的同学。
select * from student where chinese=80 and math=80;
-- 查询英语80或者总分200的同学
select * from student where english=80 and (chinese+english+math)=200;
-- 对数学成绩降序排序输出,然后再按照从高到低的顺序输出。
select * from student order by math desc;
-- 对姓李的学生总分成绩排序输出
select * from student where name like '李%' order by (chinese+english+math) desc;
update student set gender = '男' where name = '王五';
-- 查询男生和女生分别多少人,并将人数降序排序输出,查询出人数大于4的性别人数信息。
select gender,count(*) as total_cnt from student group by gender having total_cnt >= 4 order by total_cnt desc;
-- 例子2-----
create table mydb2.emp(
empno int, -- 员工编号
ename varchar(50), -- 员工名字
job varchar(50), -- 工作名字
mar int, -- 上级领导编号
hiredate date, -- 入职日期
sal int, -- 薪资
comn int, -- 奖金
deptno int -- 部门编号
);
insert into emp values(7369,'smith','clerk',7902,'1980-12-17',800,null,20);
insert into emp values(7499,'allen','salesman',7698,'1980-02-20',1600,300,30);
insert into emp values(7521,'ward','salesman',7698,'1980-02-22',1250,500,30);
insert into emp values(7566,'jones','manager',7839,'1980-04-02',2975,null,20);
insert into emp values(7654,'marttn','salesman',7698,'1980-09-28',1250,1400,30);
insert into emp values(7698,'blake','manager',7839,'1980-05-01',2850,null,30);
insert into emp values(7782,'clark','manager',7839,'1980-06-09',2450,null,10);
insert into emp values(7788,'scott','analyst',7566,'1980-04-19',3000,null,20);
insert into emp values(7839,'king','president',null,'1980-11-17',5000,null,10);
insert into emp values(7844,'turner','salesman',7698,'1980-09-08',1500,0,30);
insert into emp values(7876,'adams','clerk',7788,'1980-05-23',1100,null,20);
insert into emp values(7900,'james','clerk',7698,'1980-12-03',950,null,30);
insert into emp values(7902,'ford','analyst',7566,'1980-12-03',3000,null,20);
insert into emp values(7934,'miller','clerk',7782,'1980-01-23',1300,null,10);
-- 按员工编号升序排列不在10号部门工作的员工信息
select * from emp where deptno not in (10) order by empno asc;
select * from emp where deptno != 10 order by empno asc;
-- 查询姓名第二个字母不是"A",且薪水大于1000元的员工信息,按年薪降序排列
-- 年薪:12*月薪+奖金
-- ifnull(comm,0) 如果comm的值为null,则当做0,不为null,则还是原来的值
select * from emp where ename not like '_a%' and sal>1000 order by (12*sal+ifnull(comn,0)) desc;
-- 求每个部门的平均薪水
select deptno,avg(sal) from emp group by deptno;
select deptno,avg(sal) as avg_sal from emp group by deptno order by avg_sal desc;
-- 求个部门的最高薪水
select deptno,max(sal) max_avg from emp group by deptno;
-- 求每个部门每个岗位的最高薪水
select deptno,job,max(sal) from emp group by deptno,job order by deptno,job;
-- 求平均薪水大于2000的部门编号
select deptno, avg(sal) avg_sal from emp group by deptno having avg_sal >2000;
-- 将部门平均薪水大于1500的部门编号列出来,按部门平均薪水降序排列
select deptno, avg(sal) avg_sal from emp group by deptno having avg_sal >1500 order by avg_sal desc;
-- 选择公司中的有奖金的员工姓名,工资
select *from emp where comn is not null;
-- 查询员工最高工资和最低工资的差距
select max(sal)-min(sal) from emp;
该内容主要是本人对哔站up黑马程序员的mysql课程的学习总结!
结~~~