SQL 分组与排序
首先,这是我的表 group_student 中的行/数据
g_id |user_id |group_no |is_leader
4 1 3 0
3 9 5 0
5 10 5 0
6 11 1 0
我在对表中的行进行分组时遇到了一些问题。现在我正在使用这个 脚本。
SELECT *
FROM (groups_student)
group by group_no
它给了我这个结果:
g_id |user_id |group_no |is_leader
6 11 1 0
4 1 3 0
3 9 5 0
g_id 5 丢失了。我想如果你使用 group by 它将按行分隔行 组号。在我的 group_by 中添加另一个列字段可以做到这一点,但它会搞砸 我的观点,因为我使用的是 foreach 循环。我如何显示 g_id 5 并将其分组。
First of all this is the rows/data inside my table group_student
g_id |user_id |group_no |is_leader
4 1 3 0
3 9 5 0
5 10 5 0
6 11 1 0
I'm having a bit of problem of grouping the rows in my table. Right now I'm using this
script.
SELECT *
FROM (groups_student)
group by group_no
and it's giving me this result:
g_id |user_id |group_no |is_leader
6 11 1 0
4 1 3 0
3 9 5 0
The g_id 5 is missing. I thought if you used group by it will segregate the rows by their
group_no. Adding another column field in my group_by would do it but it will mess up
my view since I am using a foreach loop. How can I show the g_id 5 and also have it grouped.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您执行 SQL 分组时,具有与组规范匹配的字段的所有行都会折叠成一行。通常,为该分组返回的值是遇到的第一个值,在您的情况下为
g_id = 3
。如果要检索所有行以及“组”值,则应使用 SORT 子句。这将返回所有行,并将排序依据值“分组”在一起。
SQL 中的分组适用于当您想要在组的成员之间使用聚合函数(总和、计数、平均值等)时。排序适用于您不想聚合事物,而是将相似的记录放在一起的情况。
由于您的查询中没有聚合函数,因此组子句更多地充当“选择不同”的角色。
When you do an SQL grouping, all rows with fields that match the group specification COLLAPSE into a single row. Generally the value that's returned for that grouping is the first value encountered, which in your case is the
g_id = 3
.If you want to retrieve all the rows, with the "group" values together, you should use a SORT clause instead. That'd return all rows, with the sort-by values "grouped" together.
Grouping in SQL is for when you want to use the aggregate functions (sum, count, average, etc...) across the members of a group. Sorting is for when you don't want to aggregate things, but keep the similar records together.
As your query doesn't have an aggregate function in it, the group clause is acting as more of a "select distinct" instead.
您到底想从查询中得到什么?要更好地了解
GROUP BY
的工作原理,请执行以下操作:g_id
5 只是缺少,因为它被“折叠”了。What exactly is it that you're wanting to get out of the query? To get a better idea of how
GROUP BY
works, do this:g_id
5 is only missing because it's "folded in."使用 ORDER BY 而不是 GROUP BY(在本例中)。
在此处了解有关差异的更多信息。
Use ORDER BY instead of GROUP BY (in this case).
Read more about differences here.