【sql】使用group by后的查找问题
先引用百度知道中对group by 的一段解释:
GROUP BY 是分组查询, 一般 GROUP BY 是和 聚合函数配合使用,你可以想想
你用了GROUP BY 按 ITEM.ITEMNUM 这个字段分组,那其他字段内容不同,变成一对多又改如何显示呢,比如下面所示
A B
1 abc
1 bcd
1 asdfg
select A,B from table group by A
你说这样查出来是什么结果,
A B
abc
1 bcd
asdfg
右边3条如何变成一条,所以需要用到聚合函数,比如
select A,count(B) 数量 from table group by A
这样的结果就是
A 数量
1 3group by 有一个原则,就是 select 后面的所有列中,没有使用聚合函数的列,必须出现在 group by 后面
今天的问题就是一个这样的:
<!--根据销售品查询关注量--> <select id="selectByExampleWithAttentionCount" resultMap="AttentionCountResultMap" parameterType="cn.com.chinatelecom.ecms.pojo.GoodsUserAttention"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator, do not modify. --> select <if test="distinct"> distinct </if> t1.ts_mk_title as TS_MK_TITLE, t.offer_id, COUNT(t.user_id) AS ATTENTION_COUNT FROM QT_MY_ATTENTION T INNER JOIN ts_mk_info12500 t1 ON t.offer_id = t1.ts_mk_id INNER JOIN user_info t2 ON t.user_id = t2.userid <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> GROUP BY t.offer_id, t1.ts_mk_title <if test="orderByClause != null"> order by ${orderByClause} </if> </select>
其中QT_MY_ATTENTION是销售品与用户的关注表。这段代码没有问题,不过问题出在计算查询结果的数据量的代码上。问题代码如下:
<!--根据销售品查询关注量--> <select id="countByExampleWithAttentionCount" resultType="java.lang.Integer" parameterType="cn.com.chinatelecom.ecms.pojo.GoodsUserAttention"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator, do not modify. --> select count(*) FROM QT_MY_ATTENTION T INNER JOIN ts_mk_info12500 t1 ON t.offer_id = t1.ts_mk_id INNER JOIN user_info t2 ON t.user_id = t2.userid <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null"> order by ${orderByClause} </if> </select>
这里没有group by分组,查询的相当于是QT_MY_ATTENTION表的offer_id与user_id非空数据量,当关注某一销售品的用户多于1个时,由于没有分组,所以会将这些数据记为多笔,而不是按照销售品名与编码分组计数,所以查询结果是1W6+条,是错误的。
修正后的代码如下:
<!--根据销售品查询关注量--> <select id="countByExampleWithAttentionCount" resultType="java.lang.Integer" parameterType="cn.com.chinatelecom.ecms.pojo.GoodsUserAttention"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator, do not modify. --> select count(COUNT(t.user_id)) FROM QT_MY_ATTENTION T INNER JOIN ts_mk_info12500 t1 ON t.offer_id = t1.ts_mk_id INNER JOIN user_info t2 ON t.user_id = t2.userid <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> GROUP BY t.offer_id, t1.ts_mk_title </select>
得到正确的数据量为2025条。