sql – 如何在DBIx :: Class结果集搜索中检索每个组中的最新记录?

我在
DBIx::Class结果集搜索中使用group_by.为每个组返回的结果始终是具有最低id的组中的行(即组中最旧的行).我正在寻找一种方法来获得具有最高id的行(即组中的最新行).

问题基本上与此相同:
Retrieving the last record in each group
…除了我使用DBIx :: Class而不是原始SQL.

把问题放在上下文中:

我有一张音乐评论表

review
------
id
artist_id
album_id
pub_date
...other_columns...

任何给定的artist_id / album_id都可以有多个评论.
我想按照降序日期顺序查看最近的评论,每个artist_id / album_id不超过一次评​​论.

我尝试使用以下方法:

$schema->resultset('Review')->search(
  undef,
  {
    group_by => [ qw/ artist_id album_id / ],
    order_by => { -desc => 'pub_date' },
  }
);

这几乎可行,但返回每组中最早的评论而不是最新评论.
我怎样才能获得最新的?

最佳答案 为此,您需要依赖损坏的数据库行为.除非它们使用聚合函数(min,max等)或在group by子句中指定,否则在使用group by时,您不应该从表中选择列.

在MySQL,even the manual admits this is wrong – 虽然它支持它.

我认为您需要做的是获取评论的最新日期,使用max(pub_date):

my $dates = $schema->resultset('Review')->search({},
  {
    select   => ['artist_id', 'album_id', {max => 'pub_date'}],
    as       => [ qw(artist_id album_id recent_pub_date) ],
    group_by => [ qw(artist_id album_id) ],
  }
);

然后循环访问以获得审核:

while (my $review_date = $dates->next) {
    my $review = $schema->resultset('Review')->search({
        artist_id => $review_date->artist_id,
        album_id  => $review_date->album_id,
        pub_date  => $review_date->get_column('recent_pub_date'),
    })->first;
}

是的 – 这是更多的查询,但它是有道理的 – 如果两个评论在同一日期怎么办 – 数据库应该如何知道在select语句中返回哪一个?

点赞