在我的表中,我有两个字段:article_id
和 version
示例:
article_id | version
-----------|----------
5 | 1
5 | 2
6 | 1
我想做的是检索每个文章 ID 的最新版本。 (在我的示例中,我想检索文章 5 版本 2 对象以及文章 6 和版本 1 对象)。
问题是 mysql 正在执行 group by
而不是 order by
所以它返回给我每篇文章的第一个版本,但我想要相反的结果。
你有什么想法吗?
解决方案
select *
from article r
where r.version=(
select max(version)
from article r2
where r2.article_id = r.article_id
);
最佳答案
你的问题有点含糊,但我相信这或多或少是你想要的:
select * from ( select <table>.*, row_number() over (partition by article_id order by version desc) r from <table> ) where r = 1
The query returns one record for each (distinct) article_id. This record is the one with the highest version for the article_id returned.
So, together with a "test case", this can be seen in action:
create table tq84_resorces (
id number primary key,
article_id number not null,
version number not null
);
insert into tq84_resorces values (50, 5, 1);
insert into tq84_resorces values (60, 5, 2);
insert into tq84_resorces values (70, 6, 1);
select * from (
select
tq84_resorces.*,
row_number() over (partition by article_id order by version desc) r
from
tq84_resorces
)
where r = 1
返回:
ID ARTICLE_ID VERSION R
---------- ---------- ---------- ----------
60 5 2 1
70 6 1 1
关于SQL,OrderBy/GroupBy 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4958777/