小Q的博客

  • 首页
  • net编程
    • 产品和框架
    • 开发实例
    • 经验技巧
    • 开源组件
  • wp独立站
  • 自媒体
  • 日记本
  • 工具箱
每个程序员,都应该有一个自己的博客站
  1. 首页
  2. net编程
  3. 经验技巧
  4. 正文

MySQL中group by后max用法,许久不写会生疏

2023年2月24日 1867点热度 0人点赞 0条评论

现在的程序,连接数据库一般都是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;

 

留个坑,总结:手艺不用就会生

标签: group by max MySQL数据库 子查询 表关联
最后更新:2023年2月24日

小Q

80后中年不油腻大叔,喜欢编写代码、打羽毛球、做木制玩具。目前定居浙江杭州

打赏 点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2022 小Q的博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

浙ICP备2022019157号-2