mysql中怎么进行分组 mysql 分组语句

Mysql语法之分组数据 如何分组数据mysql中怎么进行分组,以便能汇总表内容mysql中怎么进行分组的子集 。这涉及两个新SELECT语句子句mysql中怎么进行分组,分别是GROUP BY子句和HAVING子句 。
分组允许把数据分为多个逻辑组 , 以便能对每个组进行聚集计算 。
分组是在SELECT语句的GROUP BY 子句中建立的 。
来看例子理解:
【mysql中怎么进行分组 mysql 分组语句】 mysqlselect vend_id,COUNT(*)AS num_prods from productsgroup byvend_id;
也就是不同的Id的商品总数都能分别查出来 。
除了能用GROUP BY分组数据外,Mysql还允许过滤分组,规定包括哪些分组,排除哪些分组 。
也就是HAVING子句 。
mysqlselect cust_id,COUNT(/) AS orders from orders uGROUP BY/u cust_id uHAVING/u COUNT(/) =2;
注意:这里HAVING换成WHERE是不管用的 。HAVING针对于分组 。
WHERE在数据分组前进行过滤,HAVING在数据分组后进行过滤 。
那么咱么看看怎么混合WHERE和HAVING 。
mysqlselect vend_id, COUNT( /) AS num_prods from products uwhere prod_price=10 group by/u vend_id HAVING COUNT(/) =2;
mysqlselect order_num,SUM(quantity*item_price) ASordertotal
from orderitems
GROUP BY order_num
HAVING SUM(quantity*item_price) =50
order by ordertotal;
技术分享 | MySQL 分组需求探秘前两天同事有个 MySQL 数据分组的需求mysql中怎么进行分组,如下测试数据,需要找出每个 name 分组中 create_date 最近的记录mysql中怎么进行分组:
需要注意的是,此处用的 MySQL 是5.6,最初是使用这条语句:
pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px;" select name, value, create_date, update_date from t1 group by name order by create_date desc;/pre
用这条 SQL 得到的其实只是每个 name 分组中最先插入的记录 , 然后按照 create_date 进行了降序排列 , 和原始需求,完全不同 。
此时可采用分而治之的策略 , 先做排序,再做分组:
pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px;" select * from (select name, value, create_date, update_date from t1 order by create_date desc) t group by t.name;/pre
当然,针对此需求,可能有其他方法,有兴趣的朋友,可以尝试写写,共享一下 。
可能有细心的朋友会发现个问题 , 就是上述 SQL 中的 group by,好像有些奇怪,如果按照常规,select 中的字段需要出现在 group by 中,上述语句竟然没报错?
如果我们在 MySQL 5.7 执行相同的语句:
pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px;" select name, value, create_date, update_date from t1 group by name order by create_date desc;/pre
因此从5.6升级到5.7,很可能出现这种相同的 SQL 执行结果不同的现象 , 这对兼容性测试的要求就会很高,究其原因,一方面是特性决定的,另一方面就是各种配置参数不同导致的 。
可以在5.7的 sql_mode 中删除这个 ONLY_FULL_GROUP_BY,即可达到5.6相同效果了,或者改写 SQL,例如:
pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px;" select * from t1 a where create_date = (select max(create_date) from t1 b where a.name = b.name);/pre
或者,
pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px;" select * from t1 a where not exists (select * from t1 b where a.name = b.name and b.create_datea.create_date);/pre

推荐阅读