group by 到底有什么作用?

hanml 2006-01-20 11:45:05
有一条sql语句,大家帮忙解释一下啊
select orderinfo0_.order_no as col_0_0_,
orderinfo0_.order_prefix as col_1_0_,
customer1_.cust_name as col_2_0_,
customer1_.cust_code as col_2_1_

from ORDER orderinfo0_
inner join CUSTOMER customer1_
on orderinfo0_.cust_code=customer1_.cust_code

where orderinfo0_.order_no='OR-00000019'
group by orderinfo0_.order_no

为什么这样查出的结果有很多条order_no都是OR-00000019的记录?
其实的ORDER 表中只有一条 order_no是OR-00000019的记录,和CUSTOMER表join后应该只有一条记录啊,可是加了group by 后就有很多条记录,如果去掉group by就只有一条,这是为什么?
...全文
841 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
livel_java 2021-06-24
  • 打赏
  • 举报
回复

写的韩浩

rouqu 2006-01-20
  • 打赏
  • 举报
回复
语法上是有问题的!group by的作用是针对一个结果集 对明确出来的列进行分组统计 你的SQL语句没有统计函数 所以说是不对的~
研究错误语句的结果意义不是很大
脚本无敌 2006-01-20
  • 打赏
  • 举报
回复
语法和要求的冲突问题
脚本无敌 2006-01-20
  • 打赏
  • 举报
回复
子查询和相关子查询的区别
看看相应的文章吧
jouwei 2006-01-20
  • 打赏
  • 举报
回复
gronp by 是对选取的行进行分组
hanml 2006-01-20
  • 打赏
  • 举报
回复
to yangys(杨杨) ( )
多谢,我试过你那个语句是可以的。不过可以探讨下下面两个问题
1。我也试过没有出现在group by和聚合函数中的字段也可以被查询。比如这句
select orderinfo0_.order_no as col_0_0_,
orderinfo0_.order_prefix as col_1_0_,
customer1_.cust_name as col_2_0_,
customer1_.cust_code as col_2_1_

from ORDER orderinfo0_
inner join CUSTOMER customer1_
on orderinfo0_.cust_code=customer1_.cust_code

where orderinfo0_.order_no='OR-00000019'
group by orderinfo0_.order_no,customer1_.cust_code
可以看到order_prefix 和cust_name都没有在group by和聚合函数中,但是查出的结果仍然是一条,是想要的结果。
2。按照select查询语句的处理顺序,是先根据where和having中的条件进行筛选,然后把筛选后的结果再根据group by的规定分组,按照这样的顺序,我的语句先找出来的结果应该只有一条
,进行groupby 后也应该只有一条的。不知道你是怎样的看法呢?
-狙击手- 2006-01-20
  • 打赏
  • 举报
回复
呵呵 ,是 了,语法有错
yangys 2006-01-20
  • 打赏
  • 举报
回复
楼主,你上面语句的语法明显错误.因为不包含在聚合函数中,也不包含在 GROUP BY 子句中的字段是不能出现在带有GROUP BY的查询当中的。

若只用 select orderinfo0_.order_no from ORDER orderinfo0_
inner join CUSTOMER customer1_
on orderinfo0_.cust_code=customer1_.cust_code

where orderinfo0_.order_no='OR-00000019'
group by orderinfo0_.order_no
明显只有一条记录。
hanml 2006-01-20
  • 打赏
  • 举报
回复
没人知道吗?

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧