博客
关于我
MySql各种查询
阅读量:792 次
发布时间:2023-02-12

本文共 1477 字,大约阅读时间需要 4 分钟。

数据库查询优化指南

1. 基础查询

简单查询

select * from info;
select Code as '代号', name as '姓名' from info;

条件查询

select * from car where code = 'c002';
select * from car where brand = 'b001' or power = 130;

2. 模糊查询

select * from car where name like '%奥迪%';

注意:%表示任意多个字符,_表示单个字符。

3. 排序查询

select * from car order by brand, power desc;

默认排序为升序,不需要写asc

4. 范围查询

select * from car where price between 40 and 60;

5. 离散查询

select * from car where code in('coo1','c003','c005','c007');
select * from car where code not in('coo1','c003','c005','c007');

6. 统计查询(聚合函数)

select count(code) from car; -- 查询记录数
select sum(price) from car; -- 查询总和
select max(code) from car; -- 查询最大值
select min(brand) from car; -- 查询最小值
select avg(price) from car; -- 查询平均值
select year(brithday) from dtudent; -- 提取生日的年份

7. 分页查询

select * from Car limit (n-1)*5,5; -- 取第n页,每页显示5条

8. 去重查询

select distinct Brand from Car;

9. 分组查询

select Brand, count(*) from Car group by Brand; -- 按品牌分组并统计记录数
select Brand from Car group by Brand having count(*) > 3; -- 分组后按条件筛选

10. 高级查询

连接查询(扩展字段)

select Info.Code, Info.Name, Info.Sex, Nation.Name, Info.Birthday from Info, Nation where Info.Nation = Nation.Code;

联合查询(扩展行)

select Code, Name from Infounionselect Code, Name from Nation;

子查询

无关子查询

select * from Info where Nation = (select Code from Nation where Name = '汉族');

相关子查询

select * from Car a where Oil < (select avg(Oil) from Car b where b.Brand = a.Brand);

注意事项

  • 使用group by时,注意having语句进行筛选。
  • 子查询通常用于条件限制或聚合函数中。
  • like查询中,%_的使用需要谨慎,避免过度匹配。

转载地址:http://jqbfk.baihongyu.com/

你可能感兴趣的文章
mysql加强(1)~用户权限介绍、分别使用客户端工具和命令来创建用户和分配权限
查看>>
mysql加强(2)~单表查询、mysql查询常用的函数
查看>>
mysql加强(3)~分组(统计)查询
查看>>
mysql加强(4)~多表查询:笛卡尔积、消除笛卡尔积操作(等值、非等值连接),内连接(隐式连接、显示连接)、外连接、自连接
查看>>
mysql加强(5)~DML 增删改操作和 DQL 查询操作
查看>>
mysql加强(6)~子查询简单介绍、子查询分类
查看>>
mysql加强(7)~事务、事务并发、解决事务并发的方法
查看>>
MySQL千万级多表关联SQL语句调优
查看>>
mysql千万级大数据SQL查询优化
查看>>
MySQL千万级大表优化策略
查看>>
MySQL单实例或多实例启动脚本
查看>>
MySQL压缩包方式安装,傻瓜式教学
查看>>
MySQL原理、设计与应用全面解析
查看>>
MySQL原理简介—1.SQL的执行流程
查看>>
MySQL原理简介—10.SQL语句和执行计划
查看>>
MySQL原理简介—11.优化案例介绍
查看>>
MySQL原理简介—12.MySQL主从同步
查看>>
MySQL原理简介—2.InnoDB架构原理和执行流程
查看>>
MySQL原理简介—3.生产环境的部署压测
查看>>
MySQL原理简介—6.简单的生产优化案例
查看>>