现在的程序,连接数据库一般都是ORM操作,许久不用SQL真的会疏。最近实现这样一个功能,也要折腾了一会儿才搞定。先看下需求,如下图所示。MySQL数据库的表,根据ParentCode分组,找出GoodsCode个数最大值。涉及到的SQL语法包括group by、max、子查询、表关联
方法1
select ParentCode,max(count(*)) from ba_goodscombine group by ParentCode;
[Err] 1111 - Invalid use of group function
简单说,就是MySQL不支持这种写法(好像不是标准的SQL语句)
方法2,子查询ok
select max(a.GoodsCount) from (select ParentCode,count(*) GoodsCount from ba_goodscombine group by ParentCode) a;
方法3,表关联ok
select max(b.GoodsCount) MaxGoodsCount from ba_goodscombine a left join (select ParentCode,count(GoodsCode) GoodsCount from ba_goodscombine group by ParentCode) b on a.parentcode = b.parentcode;
留个坑,总结:手艺不用就会生
文章评论