SQL语句综合使用

SQL综合使用

书写顺序:

select 查询字段 from 表名 where 限制条件 group by 分组依据 having 过滤条件 order by 排序 limit 展示条数

执行顺序:

from ------查询表

where ------限制条件

group by ------分组

having ------过滤条件

order by ------排序

limit ------展示条数

distinct ------去重

select ------查询的结果

正则查询

select * from user where name regexp 正则表达式;

聚合查询:

max ------查询最大值

min ------查询最小值

avg ------求平均数

sum ------求和

count ------统计次数

拼接:

concat

连接查询:inner join

一、单表查询:

1、where查询:

= 等于

!= 不等于

> 大于

< 小于

>= 大于等于

<= 小于等于

where id>3 and id<6 (等价于:where id between 3 and 6)

AND 与

OR 或

IN 后面可以跟随多个值(id IN(3,6)相当于id=3 or id=6)

LIKE 模糊查询(’%‘零个或多个字符,’_'一个字符)**

注意:查询为null的时候不能用等于,需要用is

2、分组(group by):

​ 分组后取出的是每个组的第一条数据

3、聚合查询:

​ max 最大值 select max(score) from 查询最高分

​ min 最小值 select min(score) from 查询最低分

​ avg 平均值 select avg(score) from 查询平均分

​ count 计数 select count(id) from student where score>=60 查询成绩大于60分的人数

4、having 过滤查询

** (语法和where一样,where后面不能使用聚合函数,但是having可以用)**

​ 示例:select * from student where 条件 group by 分组 having avg(条件列)>60

5、distinct 去重

** (对重复的数据进行去重操作)**

​ 示例:select distinct name from student (查询student表中所有出现的学生姓名)

6、order by 排序

​ order by age [asc] 根据年龄默认升序排列(从小到大)

​ order by age desc 根据年龄降序排列

​ 多条件排序(先按年龄升序,年龄相同再按身高降序排列)

​ 示例: select * from student order by age,height desc;

7、limit(限制展示条数)

​ limit num :表示从第一天数据开始展示num条

​ 示例:select * from student limt 3 (表示所有学员信息中的第三条)

​ limit num1,num2 :num1表示起始下标,num2表示从num1开始展示的条数

​ 示例:select * from student limt 0,5 (表示所有学员前5条的记录)

​ 示例:select * from student limt 5,5 (表示第6到第10条记录)

二、多表查询

1、连接查询

​ 表一 inner join 表二 on 表一和表二的关系

​ AS:起别名

2、子查询:

​ 将一个查询语句的结果作为另一个查询语句的条件

​ 示例:(查询英语成绩最高的学员信息)

​ select * from student where id =

​ (select studentId from score where englishscore=

​ (select max(englishscore) from score))

示例分解:1、先查询英语成绩的最高分:select max(englishscore) from score

​ 2、英语成绩最高的学员编号:

​ (select studentId from score where englishscore=

​ (select max(englishscore) from score))

​ 3、在通过学员编号查询学生信息:

​ select * from student where id =

​ (select studentId from score where englishscore=

​ (select max(englishscore) from score))

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值