博客
关于我
mysql之分组查询GROUP BY,HAVING
阅读量:801 次
发布时间:2023-02-11

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

一、查询格式

在编写SQL查询时,需要遵循明确的语法结构。查询列表需要包含以下关键要素:

1. **选择列和函数**:使用`select`语句指定要查询的字段和聚合函数。例如,`select column, group_function(column)`。 2. **指定表名**:明确要操作的数据库表。例如,`from table_name`。 3. **筛选条件**:在`where`子句中添加条件筛选数据。注意:`where`子句后面不能使用`group by`或`having`后的字段别名。 4. **分组操作**:在`group by`子句中指定分组依据字段。例如,`group by field`。 5. **排序子句**:在`order by`子句中定义排序规则。例如,`order by column DESC`。

需要注意的是,查询列表比较特殊,`group by`和`having`后面的字段可以使用原语句前部分定义的别名,而`where`子句后面不能使用别名。

二、分组查询的案例

在实际操作中,需要注意分组查询的逻辑顺序。对于带筛选条件的分组查询,通常分为两种类型:

1. **分组前筛选**:通过原始表数据对记录进行筛选。这种方法可以直接放在`where`子句中。 2. **分组后筛选**:筛选条件依赖于`group by`后的聚合函数结果。这种情况下,筛选条件只能放在`having`子句中。

编写分组查询时,可以按照以下步骤进行:

1. 先写出`select`、`from`、`group by`的基本框架。 2. 观察筛选条件是否可以通过`where`子句完成。如果可以,直接在`where`中添加;如果不行,则需要将其放在`having`子句中。 3. 如果筛选条件涉及聚合函数的结果,则一定要放在`having`子句中。 4. 尽量先使用`where`子句进行筛选,减少`having`子句的使用,以提高查询性能。

**示例:简单的分组查询**

假设有以下数据表`user_info`,字段包括`id`、`username`、`email`、`role`。我们需要计算不同角色的用户数量及其平均邮箱数量。以下是查询步骤:

1. 写出基本框架: ```sql select role, count(id) as user_count, avg(email) as avg_email from user_info group by role having count(id) > 1 order by user_count desc ``` 2. 分析筛选条件:`having count(id) > 1`用于筛选每个角色下用户数量大于1的记录。这里的筛选条件依赖于`group by`后的`count(id)`,因此必须放在`having`子句中。 3. 执行查询,结果会显示不同角色的用户数量及对应的平均邮箱数量,并按用户数量排序。

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

你可能感兴趣的文章
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No static resource favicon.ico.
查看>>