我有一张包含学生姓名的表格,自动增加 NR
记录,但每次编辑记录时,都会创建一个新记录,将 NR
复制到 >ID
字段。
但是当我尝试在 MAX(NR
) 时对 ID 记录进行分组时,它会显示该 ID 的最大数量,但是当我询问剩余的 rocord 时,它不会显示最后一条记录该组 ID 位于
SELECT MAX(`NR`) AS 'mNr',`NR`,`ID`,`Name1`,`Name3`,`Gender`
FROM `Kids` GROUP BY `ID`
这会产生如下结果:
mNr NR ID Name1 Name3 Gender 252 1 1 Alice Carper f 179 2 2 Dorah Fisher f 189 3 3 Racheal King f 173 4 4 Frank Smith m 192 5 5 Patrick Fay m 305 6 6 Gloria Sing f 299 7 7 Bridget Young f
But as you can see, the query shows the highest edit NR, but then continues to give the lowest of the rest of the record, not the record details belonging to that lastest NR... What am I doing wrong? This is the sample data:
NR ID Name1 Name3 Gender
1 1 Alice Achand f
2 2 Dorah Achieng f
3 3 Racheal Achieng f
4 4 Francisca Adikin f
5 5 Patrick Adilu m
6 6 Gloria Ajwang f
7 7 Bridget Aketch f
130 5 Patrick Adilu m
129 4 Francisca Adikin f
128 2 Dorah Achieng f
153 4 Francisca Adikin f
173 4 Francisca Adikin f
179 2 Dorah Achieng f
189 3 Racheal Achieng f
192 5 Patrick Adilu m
252 1 Alice Wor f
299 7 Bridget Aketch f
305 6 Gloria Ajwang f
最佳答案
也许您不知道,您正在使用 MySQL 的一个神秘功能。 MySQL 允许您在聚合查询的 select
语句中包含不在聚合函数或 group by
子句中的列。引擎为这些列输入任意值。
做你想做的事情的正确方法是使用连接:
SELECT k.*
FROM `Kids` k join
(select id, max(nr) as maxnr
from kids
group by id
) m
on k.id = m.id and nr = maxnr;
以下是文档中的明确解释:
MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. This means that the preceding query is legal in MySQL. You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. Sorting of the result set occurs after values have been chosen, and ORDER BY does not affect which values within each group the server chooses.
您可以更详细地阅读 here .
关于mysql - 显示包含最新编辑版本的所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19755246/