Mysql查询语句进阶知识集锦
Python进阶学习交流前言
上次咱们简单的学习了一下select的用法,大概有了一些基本的了解。
咱们接着上次继续来看叭!
查询
数据如下

or查询
我们在上学时,会听到这样的话,某某某,你把谁谁谁或者谁谁谁叫过来。
这样子的话,我们我们要查询的,就是一个或(or)的关系了。
or查询只有满足一个条件即可
sql
-- 语法SELECT * from student WHERE <条件> or <条件> ...;-- 例如,查询姓名为张三的或者姓名为小刘的数据SELECT * from student WHERE name="张三" or name="小刘";
执行结果

不等于(!=)查询
上述我们查询的,都是等于(=)操作,但是我们在上学时,还会有这种情况。
某个学生学习可好,背东西背的可快,放学的时候可能就人家一个人过了,这时候老师可能就说
除了某某某,其他学生本篇文章全部抄3遍,淦。。。
所以这时候就是反过来的查询的,只需要排除某个人即可!
sql
-- 语法SELECT * from student WHERE <条件>;-- 例如,查询姓名不是张三的其他人,排除张三SELECT * from student WHERE name!="张三";
执行结果

in/not in查询
学生们还都是年轻人,年龄大概都在20来岁,这时候老师说,班长,把年龄在19,20,21的人统计一下!
根据上述我们学过的知识,可能你是这样婶的。
SELECT * from student WHERE age=19 or age=20 or age=21;
执行结果

通过三个or找到,其实这样也没错,但是还有一种更简单的。
sql
-- 语法SELECT * from student WHERE <列名> in (值1,值2,...) ...;-- 例如,需求同上SELECT * from student WHERE age in (19,20,21);
执行结果

not in 就是不在这个范围的数据啦!
sql
-- 查询年龄不在19,20,21范围的数据SELECT * from student WHERE age not in (19,20,21);
执行结果

between查询
between适合进行范围查询!
sql
-- 语法select * from 表 where <列> between <开始范围> and <结束范围>;-- 例如,查询年龄时20-22岁的学生SELECT * from student WHERE age BETWEEN 20 and 22;
执行结果

同理,between还能用在时间上。
select * from <表名> where <时间列> between <开始时间> and <结束时间>
模糊查询(like)
假设现在数据如下,有三个姓张的。

老师可能突然有一天对你说,班长,把咱们姓张的列出来,我找他们谈点事,咋办???
我们只需要找,是以张开头的,后面是啥无所谓。
所以就要用到like模糊查询。
sql
-- 语法 %表示匹配一个或多个字符select * from 表 where <列> like '[%]<字符串>[%]'-- 例如,查询,以张开头的SELECT * from student WHERE name like "张%";
执行结果

同理,这个%可以放在任意位置,他就是充当不确定的字符使用的,能够自动匹配一个或多个。
例如
... WHERE name like "张%丰";
匹配:张三丰
WHERE name like "%鱼";
匹配:张甲鱼
WHERE name like "李%";
匹配:李四
...
限制(limit)
限制这个有点怪异,还是图片举例比较好。
数据如下

sql
-- 前两行SELECT * from student LIMIT 2;

-- 从第2行开始后,再取4行SELECT * from student LIMIT 2,4;-- 同上,写法不同SELECT * from student LIMIT 4 OFFSET 2

排序(order by)
不知道你有没有发现,我们之前查找的顺序都是正向的。

但是会有个问题,我们新增的数据,其实id是最大的,理论来说,应该要排在最前面。
所以,应该是倒序的是最好的。
sql
-- 语法select * from <表名> order by <列> asc -- 从小到大排序select * from <表名> order by <列> desc -- 从大到小排序select * from <表名> order by <列1> desc,<列2> asc -- 先根据 列1 排序,如果数据相同,按照 列2 排序
例如
根据id正向排序
SELECT * from student ORDER BY id ASC;
执行结果

根据id反向排序
SELECT * from student ORDER BY id desc;
执行结果

hhh,这样我们就把数据反过来了!!!
分组(groupby)
分组,这个可能是难为了一批人,其实分组的核心,在于理解这个压缩这个概念。
假设数据如下

性别有男有女,如果我想知道,男的有多少个,女的有多少个怎么办???我总不能数吧。。。
所以这时候,如果能吧,男的都拿出来,女的都拿出来,就像这样!

然后我对拿出来进行压缩成一条。

如果这个你懂了,那分组就懂了。
语法
SELECT <列>,COUNT(<列>) from student GROUP BY <列>;-- 因为分组了某个列,所以就不能再展示其他列的信息了,因为压在一块了,显示不了-- 但是可以通过count,sum等函数计算压缩的个数,或者总值
例如
统计男女各多少人
SELECT gender,COUNT(gender) from student GROUP BY gender;
执行结果

统计同一年龄多少人
SELECT age,COUNT(age) as "数量" from student GROUP BY age;
执行结果

注意:group by必须在where之后,order by之前。
总结
本篇主要讲述的是Mysql查询语法,再单表查询中,基本上就上述这么些的内容,但是从理论到事件,是需要时间的。
一定要勤加练习,什么是or查询,like查询注意事项,尤其是group by分组查询,一定要多多思考和联系。
如果在操作过程中有任何问题,记得下面留言,我们看到会第一时间解决问题。
不要轻易改变自己,因为你可能就是世界上那颗未加工的最亮的钻石。
我是码农星期八,如果觉得还不错,记得动手点赞一下哈。
感谢你的观看。
如果在操作过程中有任何问题,记得下面留言,我们看到会第一时间解决问题。