mysql 多表查讯的表达式 归纳总结

本文深入解析SQL查询语句的构造与应用,涵盖from、where、group by、order by及limit子句的使用技巧,通过实例展示如何高效检索、排序与统计数据库信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

查询数据的表达式

from子句

# 字段用','隔开,至少有一个字段,最终结果集按照这个这个顺序显示
select 字段1,字段2... from 表名;

# *代表所有字段
select * from 表名;
distinct(去重)
# 去重后的结果,distinct必须紧接着select后面
select distinct 字段 from 表名;

# 统计不重复的个数
select count(distinct 字段) from 表名;

where子句

类型 运算符
算术 + - * / %
比较 > < >= <= != =
逻辑 or || and && not !
提升优先级 ( )

案例:
# 搜索id<20的所以数据
select * from students where id<20;

# 搜索id编号为偶数的数据
select * from students where id%2=0;
where条件关键字
in:查询一个集合的数据
# 搜索id在(1,3,7)之中的数据
select * from students where id=1 || id=3 || id=7;
select * from students where id in(1,3,7);

# 一次删除多条记录
delete from students where id=3 || id=15 || id=23;
delete from students where id in(3,15,23);
between...and... :查询一个区间的数据
# 搜索id在20-40之间的数据
select * from students where id>20 && id<40;
select * from students where id between 20 and 40;

# 删除id在20-40之间的数据
delete from students where id between 20 and 40;
not:排除
# 搜索id除了20-40之间的数据
select * from students where id not between 30 and 40;

like 子句

用于模糊查询 %:任意字符长度 _ :一个字符长度
# 搜索name名字以5结尾的数据
select * from students where name like '张%';

# 搜索name名字包含字母s的数据
select * from students where name like '%二%';

# 搜索id以5结尾的两位数 数据
select * from students where id like '_5';

limit 子句

控制查询记录条数,数据表中的记录,索引从0开始
select * from students limit 2 # 返回两条记录
select * from students limit 3,4 # 从索引为3的记录开始,返回4条记录

# php中的分页功能,偏移值的计算:(当前页-1) * 每页记录数
select name from student limit 4 offset 3
# 还可以使用offset(偏移):从索引为3的记录开始,返回4条

group by(结果分组)

根据给定数据列的每个成员对查询结果进行分组统计,最终得到一个分组汇总表
利用group by分组信息进行统计,常见的是配合max等聚合函数筛选数据后分析。
select指定的字段要么作为分组的依据(Group By语句的后面),要么就要被包含在聚合函数中。
#  简单分组
select sex from students group by sex;
+-----+
| sex |
+-----+
| m   |
| w   |
+-----+

# 聚合函数分组
select count(*),city from students group by city;
+----------+----------+
| count(*) | livecity |
+----------+----------+
|        7 |        1 |
|        8 |        2 |
|        1 |        3 |
|        3 |        4 |
|        2 |        5 |
+----------+----------+

order der(结果排序)

按照给定的字段进行排序,asc:升序(默认) desc:降序
如果同时选择多个字段,先按第一个字段排序,如果第一个字段值相等,再尝试第二个字段,以此类推
# 默认升序
select * from students order by birthday;

# 降序
select * from students order by birthday desc;
查询语句的书写顺序
select →字段→ from→表名→where→group by→order by→limit 
别名
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一拳超人up

一分也是情

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值