在我的表中,我有两个领域:article_id和version
例:
article_id | version
-----------|----------
5 | 1
5 | 2
6 | 1
Run Code Online (Sandbox Code Playgroud)
我想要做的是检索每个文章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
);
Run Code Online (Sandbox Code Playgroud)
你的问题有点模糊,但我相信或多或少是你想要的:
select * from (
select
<table>.*,
row_number() over (partition by article_id order by version desc) r
from
<table>
)
where r = 1
该查询为每个(不同的)article_id返回一条记录.此记录是返回的article_id版本最高的记录.
因此,与"测试用例"一起,可以看到这一点:
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
Run Code Online (Sandbox Code Playgroud)
返回:
ID ARTICLE_ID VERSION R
---------- ---------- ---------- ----------
60 5 2 1
70 6 1 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
181 次 |
| 最近记录: |