mybatis group by 分组查询
时间: 2023-10-18 12:31:00 浏览: 256
mybatis分页查询
4星 · 用户满意度95%
在MyBatis中,可以使用GROUP BY关键字进行分组查询。分组查询可以按照某个字段或多个字段中的值进行分组,相同值的记录会被归为一组。同时,可以使用聚合函数对每个分组进行统计计算。以下是几个示例:
1. 按照性别分组统计学生数量:
SELECT sex, COUNT(id) FROM student GROUP BY sex
2. 按照地址分组统计学生数量:
SELECT address, COUNT(id) FROM student GROUP BY address
3. 按照地址和性别分组统计学生数量:
SELECT address, sex, COUNT(id) FROM student GROUP BY address, sex
4. 按照地址和性别分组统计学生数量,并筛选出性别为1的结果:
SELECT address, sex, COUNT(id) FROM student GROUP BY address, sex HAVING sex = 1
在MyBatis中,可以使用XML配置文件或注解来编写以上查询语句,并通过调用相应的方法来执行查询操作。比如使用XML配置文件可以这样写:
<select id="groupQuery" resultType="java.util.HashMap">
SELECT sex, COUNT(id) FROM student GROUP BY sex
</select>
<select id="groupQuery" resultType="java.util.HashMap">
SELECT address, COUNT(id) FROM student GROUP BY address
</select>
<select id="groupQuery" resultType="java.util.HashMap">
SELECT address, sex, COUNT(id) FROM student GROUP BY address, sex
</select>
<select id="groupQuery" resultType="java.util.HashMap">
SELECT address, sex, COUNT(id) FROM student GROUP BY address, sex HAVING sex = 1
</select>
然后通过调用相应的方法来执行查询操作。例如,调用addressStudent方法来执行按地址分组统计学生数量的查询:
List<HashMap<String, Long>> addressStudent(); <span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [Mybatis之分组查询](https://blog.csdn.net/leijie0322/article/details/124103798)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文