【发布时间】:2012-05-22 02:56:40
【问题描述】:
我明白这在许多人看来可能是一个愚蠢的问题,但我无法在任何地方找到关于“分组依据”对 SQL 语句中的 select max(...) 的影响的明确解释。
我有以下数据(还有另一个未显示的 mediumblob 类型的列图像):
id title test_id
1 bomb 0
2 Soft watch 2
3 Dali 1
4 Narciss 1
5 The Woman In Green 0
6 A summer in Vetheuil 0
7 Artist's Garden 2
8 Beech Forest 2
9 Claude Monet 0
我知道我是否执行
select max(id) from images
where image is not null;
我得到了 id 的最大值,即:
max(id)
9
但是有人可以解释一下我表演时发生了什么
select max(id), title, test_id
from images
where image is not null
group by id;
我发现 max(id) 没有任何用处(结果如下所示)?
max(id) title test_id
1 bomb 0
2 Soft watch 2
3 Dali 1
4 Narciss 1
5 The Woman In Green 0
6 A summer in Vetheuil 0
7 Artist's Garden 2
8 Beech Forest 2
9 Claude Monet 0
【问题讨论】:
-
你想从表中获取最新的行吗?表中的最后一行(更准确地说)。
-
由于 ID(通常)是唯一的,因此按 ID 分组将创建 1 个组。
-
尝试用
GROUP BY test_id替换它,看看会发生什么。 -
为什么查询没有返回单行“9 Claude Monet 0”?
-
@Alastair:因为您按
id分组。因此,对于每个唯一的id,它将返回该组中最高的id。由于id是唯一的,因此每个“组”包含 1 条记录。那么,每个组的最大值就是该记录。