SQL,OrderBy / GroupBy的问题

时间:2011-02-10 15:09:14

标签: sql oracle

在我的表格中,我有两个字段:article_idversion

示例:

   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
);

5 个答案:

答案 0 :(得分:5)

你的问题有点模糊,但我相信这或多或少是你想要的:

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

返回:

        ID ARTICLE_ID    VERSION          R
---------- ---------- ---------- ----------
        60          5          2          1
        70          6          1          1

答案 1 :(得分:2)

select yt.id, yt.article_id, yt.version
    from (select article_id, max(version) as max_version
              from YourTable
              group by article_id) t
        inner join YourTable yt
            on t.article_id = yt.article_id
                and t.max_version = yt.version

答案 2 :(得分:2)

select
    article_id,
    max(version) as Version

from article

group by article_id

答案 3 :(得分:1)

首先,您应该将版本列更改为整数(如果您非常需要字符串,可以使用前缀列),而不是

Select MAX(version) 
...
Group By article_id

答案 4 :(得分:1)

这会起作用吗?

select articleId, (select top 1 version 
                  from article ar2 
                  where ar2.articleId = ar.articleId
                  order by version desc) as version
from article ar
group by ar.articlId

在sql server 2005中运行,没有在mysql中测试。

相关问题