数据查询,简单查询及高级查询
查询所有列
1.select * from info
查特定列
2.select code,name from info
查出列后加别名,再查姓名
3.select code as '代号',name as '姓名' from info
条件查询,单条件查询
4.select * from info where code='p001'
两个条件,并且的关系
5.select * from info where code='p001' and nation='n001'
范围查询
6.select * from car where price between 20 and 50
离散查询,关键字in
7.select * from car where price in(20,30,40)
模糊查询,使用关键字来查,关键字like,后面跟字符串
8.select * from car where name like '%奥迪%'
排序,根据某一列,默认的是升序
9.select * from car order by price desc
去重查询
10.select distinct brand from car
分页查询,关键字limit,数字分别表示跳过几条数据,显示几条数据
11.select * from car limit 5,5
聚合函数,count代表数量,sum求和 平均 最大值 最小值
12.count() sum() avg() max() min()
分组查询,主要用来做统计,根据brand来分
13.select brand,count(*) from car group by brand
高级查询
1.连接查询,对结果集列的扩展
select * from info
select * from info,nation #形成笛卡尔积(连接两张或多张表,数据量小的时候可以用)
select * from info,nation where info.nation=nation.code(用条件来筛选,如果有重复的,一定要先写表名,没有重名的就可以直接写)
select info.code,info.name,sex,nation.name,birthday from info,nation where info.nation=nation.code(筛选出自己想要的数据)
select * from info join nation on info.nation=nation.code(关键字join后面加条件,如果只运行前半句select * from info join的话,和上面的情况一样,会出现笛卡尔积,和join配合使用的是on,on后面加连接条件)
2.联合查询,对结果集行的扩展
select code,name from info
union(关键字,联合显示两张表,查的列的数量要相同)
select code,name from nation
3.子查询
父查询:外层查询
子查询:里层查询
子查询的结果做为父查询的条件
(1)无关子查询
子查询在执行的时候和父查询没有关系,子查询可以单独执行
1.查询民族为‘汉族’的所有人员信息
父查询:select * from info where nation=()
子查询:select code from nation where name='汉族'
(整合,子查询的结果当做父查询的条件)select * from info where nation=(select code from nation where name='汉族')
2.查询系列名为‘宝马5系’的所有汽车信息
select * from car where brand=(select brand_code from brand where brand_name='宝马5系')
(2)相关子查询
子查询在执行的时候和父查询有关系,子查询不可以单独执行
1.查询汽车表中油耗小于该系列平均油耗的所有汽车信息
父查询:select * from car where oil<(该系列平均油耗)
子查询:select avg(oil) from car where brand=该系列
select * from car as a where oil<(select avg(oil) from car as b where b.brand=a.brand)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?