这是我参与8月更文挑战的第11天,活动详情查看:8月更文挑战
前言
哈喽,各位掘友们大家好,了解过数据库的后端小伙伴肯定对SQL再熟悉不过,数据的增删改查也是得心应手,不过现在对于前端来说,了解SQL相关操作,也是必不可少的技能了。
语法格式:SQL语句,不区分大小写
-- 基本的查询语法
SELECT 字段1,字段2,... FROM 表名
select 字段,字段,.... from 表名
-- 查询所有的字段
SELECT * FROM 表名
-- 带条件的查询
SELECT * FROM 表名 [WHERE 条件] [ORDER BY 排序字段[, 排序字段]] LIMIT [开始位置,]长度
1 基本查询
格式: select 字段名1, 字段名2,.... from 表名 案例1: 查询所有候选人的姓名和昵称
select name,nickname from candidate
案例2: 查询全部候选人的全部信息
select * from heroes
2. 带where子句的查询
select field1, field2... from 表名 查询表中的所有数据
where 可以使用条件来筛选查询出的结果
-- 查询id小于10的候选人
-- select * from candidate where 条件
-- select * from candidate where id<10
-- 查询id小于20的女候选人
-- select * from candidate where id<20 and sex='女'
-- 查询年龄大于等于20小于等于30的候选人
-- select * from candidate where age>=20 and age<=30
-- select * from candidate where age between 20 and 30
3 模糊查询
通配符:
- %: 代表任意长度(包括0)的任意字符
- _: 代表1位长度的任意字符
like: 在执行模糊查询时,必须使用like来作为匹配条件
-- select * from candidate where name like '%龙%'
-- 查询名字的最后一个字是 “龙” 的候选人
-- select * from candidate where name like '%龙'
-- 查询名字中带有 “龙” ,并且要求 “斯”前面只能有一个字的候选人
select * from candidate where name like '_龙%'
4.统计查询
- max 查询最大值
select max(age) from candidate - Min 查询最小值
select min(age) from candidate - avg 查询平均值
select avg(age) from candidate - sum 查询总和(查询所有候选人的年龄之和)
select sum(age) from candidate - count 查询总记录数(查询共计有多少个候选人)
select count(*) cc from candidate
-- 查询所有候选人中年龄最大的的年龄
-- select max(age) from candidate
-- 查询所有候选人中年龄最小的的年龄
-- select min(age) from candidate
-- 查询所有候选人年龄的平均值
-- select avg(age) from candidate
-- 查询所有候选人的年龄之和
-- select sum(age) from candidate
-- 查询共计有多少个候选人
-- select count(*) from candidate
-- 查询共计有多少候选人,用cc表示
-- select count(*) cc from candidate
5 查询结果排序
order by 可以对查询结果按某个字段进行升序或者降序排列
- 升序 asc (默认值)
- 降序 desc
可进行排序的字段通常是 整型 英文字符串型 日期型 (中文字符串也行,但一般不用)
-- select * from candidate order by 排序字段 asc/desc
-- asc 默认值,可以省略,表示升序
-- desc,表示降序
-- 查询所有的候选人,按年龄升序排序
-- select * from candidate order by age asc
-- select * from candidate order by age
-- 查询所有的候选人,按年龄降序排序
-- select * from candidate order by age desc
-- 查询所有的候选人,先按年龄降序排序;如果年龄相同的,再按id降序排序
-- select * from candidate order by age desc, id desc
-- 查询年龄大于50岁的候选人,并按年龄降序排序
select * from candidate where age>50 order by age desc
注意:如果SQL语句中,有where和order by,where一定要放到order by之前。
6 限制查询结果
limit 用来限制查询结果的起始点和长度
-
格式: limit start, length
- start: 起始点。 查询结果的索引,从0开始。 0代表第一条数据。如果省略start,则默认表示从0
- length: 长度
-- 查询所有候选人中前5个候选人
-- select * from candidate limit 起始位置, 长度
-- select * from candidate limit 0, 5
-- select * from candidate limit 5
-- 查询所有候选人中,第6到10个候选人
-- select * from candidate limit 5, 5
-- 查询年龄最大的3个候选人
-- select * from candidate order by age desc limit 3
-- 查询年龄最大的3个女候选人
select * from candidate where sex='女' order by age desc limit 3
注意:where、order by、limit如果一起使用,是有顺序的,where在最前面、其次是order by、limit要放到最后。另外三者之间没有and之类的。
总结:
今天的分享就到这里啦,欢迎小伙伴们,批评指正,也希望这篇文章给你们 提供一些帮助。