MYSQL中的DQL

先看SQL语句的完整格式:

复制代码
SELECT select_expr [,select_expr,...] [ 
    FROM tb_name 
    [JOIN 表名] 
    [ON 连接条件] 
    [WHERE 条件判断] 
    [GROUP BY {col_name | postion} [ASC | DESC], ...] 
    [HAVING 条件判断] 
    [ORDER BY {col_name|expr|postion} [ASC | DESC], ...] 
    [LIMIT {[offset,]rowcount | row_count OFFSET offset}] 
]
复制代码

 

SQL语句的条件控制:

  where之比较运算

    常⻅的⽐较运算符有 >,<,>=,<=,!=
select name,age,height,gender from students where id>10;

  where之逻辑运算

    逻辑运算符and表示and连接的多个条件同时成⽴则为真,or表示or连接的多个条件有⼀个成⽴则为真,not表示对条件取反
  
select id,name,age from students where not (id>5 and id<10);

  where之模糊查询

    like和%结合使⽤表示任意多个任意字符,like和_结合使⽤表示⼀个任意字符
elect name,age from students where age like '1%';

  where之范围查询

    bettween-and限制连续性范围 in限制⾮连续性范围
select name,age from students where age between 18 and 30;
select name,age from students where age in(18,28);

  where之空值判断sel

    判空⽤IS NULL 判⾮空⽤ IS NOT NULL
select * from students where height is null;

SQL查询语句

  DQL的排序:

select * from 表名 order by 列1 asc|desc [,列2 asc|desc,...]

  聚合函数:

  MYSQL中常见的聚合函数:

    

   group分组:

select gender,group_concat(name) from students group by gender;
select gender,group_concat(id) from students group by gender;
select gender,avg(age) from students group by gender;
select gender,group_concat(age) from students group by gender with rollup;

    通过having表达式来过滤分组结果:

select gender,count(*) from students group by gender having count(*)>2;

  限制记录: select * from students limit 5,3; 

    默认下标从0开始。

   连接:

    mysql中支持三种类型的连接查询,分别是:

      内连接查询:查询的结果为两个表匹配到的数据。

        

 

      右外连接查询:查询的结果为两个表匹配到的数据和右表特有的数据,对左表中不存在的数据用null填充。

        

      左外连接查询:查询的结果为两个表匹配到的数据和左表特有的数据,对右表中不存在的数据用null填充。

          

      示例: select * from students stu inner join classes cls on stu.cls_id=cls.id; 

    自连接:

select * from areas city inner join areas province on city.pid = province.aid where province.atitle='广州市';

  子查询:

    在⼀个 select 语句中,嵌⼊了另外⼀个 select 语句, 那么被嵌⼊的 select 语句称之为⼦查询语句,外部那个select语句则称为主查询。

    主查询和⼦查询的关系

      ⼦查询是嵌⼊到主查询中⼦查询是辅助主查询的,要么充当条件,要么充当数据源⼦查询是可以独⽴存在的语句,是⼀条完整的 select 语句。

    子查询的分类

      1.标量子查询 select * from students where age > (select avg(age) from students); 

      2.列子查询 select name from classes where id in (select cls_id from students); 

      3.行子查询

select * from (select * from students where gender='') as stu where height>180;

 -------------------------------------------------- 花有重开日,人无再少年... -----------------------------------------------------

      

 

 

     

posted @   Avery_rainys  阅读(30)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示