1

我有一张桌子:

id_object | version | document
------------------------------
1         | 1       | 1 
1         | 2       | 2 
2         | 1       | 3 
2         | 2       | 1 
2         | 3       | 2 
1         | 1       | 3 

我只想按对象显示一行,其中包含版本(最大)和文档。我已经尝试了以下“

Select Distinct
  id_object ,
  Max(version),
  document
From
  prods
Group By
  id_object, document

我得到了这个结果

1         | 1       | 1
1         | 2       | 2
2         | 1       | 3
2         | 2       | 1
2         | 3       | 2
1         | 1       | 3

正如你所看到的,我得到了整张桌子。我的问题是,为什么?

4

3 回答 3

2

由于您按id_object and document分组,因此您将无法获得所需的结果。那是因为document每个人都不一样version

select x.id_object, 
       x.maxversion as version,
       p.document
from 
(
   Select id_object, Max(version) as maxversion
   From prods
   Group By id_object
) x
inner join prods p on p.id_object = x.id_object 
                   and p.version = x.maxversion

您首先必须id_object选择max(version). 这可以与实际数据相结合以获得正确的document.

您必须这样做,因为您不能选择不在您的group by子句中的列,除非您对它们使用聚合函数(max()例如)。

(MySQL 可以选择非聚合列,但请避免这样做,因为结果并不总是清晰甚至无法预测)

于 2013-02-14T11:01:22.187 回答
0

询问:

SQLFIDDLE示例

SELECT p.id_object, 
       p.version, 
       p.document
FROM prods p
WHERE p.version = (SELECT Max(version)
                   FROM prods
                   WHERE id_object = p.id_object)

结果:

| ID_OBJECT | VERSION | DOCUMENT |
----------------------------------
|         1 |       2 |        2 |
|         2 |       3 |        2 |
于 2013-02-14T11:20:49.583 回答
0
select prods.id_object, version, document
from prods inner join
(select id_object, max(version) as ver
from prods
group by id_object) tmp on prods.id_object = tmp.id_object and prods.version = tmp.ver
于 2013-02-14T11:02:28.777 回答