2011-08-22 21 views
4

我在DBIx::Class結果集搜索中使用group_by。每個組返回的結果總是具有最低id的組中的行(即組中最早的行)。我正在尋找一種方法來獲得最高id的行(即組中最新的一行)。如何在DBIx :: Class結果集搜索中檢索每個組中的最新記錄?

問題與此基本相同: 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' }, 
    } 
); 

這幾乎工程,但各組,而不是在最新的返回最古老的審查。 我怎樣才能得到最新的?

+0

也許'-desc' =>'-asc'? – J0HN

+0

J0HN - order_by在分組完成後應用,因此它不會影響每個組返回的結果。 – nick

回答

2

對於這個工作,您依賴於破損的數據庫行爲。當您使用組時,除非它們使用聚合函數(最小值,最大值等)或在group by子句中指定,否則不應該能夠從表中選擇列。

在MySQL中,even the manual admits this is wrong - 儘管它支持它。

我現在想什麼,你需要做的是得到的評論最新的日期,用最多(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; 
} 

是的 - 它是更多的查詢,但它是有道理的 - 如果兩個評論是在同一日期 - 如何DB應該知道在select語句中返回哪一個?

相關問題