MySQL每组最多2条记录

时间:2015-10-13 02:11:15

标签: mysql sql

基本上我需要为每个用户只获取最后2条记录,考虑到最后的created_datetime:

2  | 34      | '2015-10-11'
1  | 34      | '2015-09-10'
7  | 159     | '2015-10-03'
8  | 159     | '2015-10-06'

返回(预期输出):

select user_id, created_datetime, 
$num := if($user_id = user_id, $num + 1, 1) as row_number, 
$id := user_id as dummy 
from logs group by user_id 
having row_number <= 2 

我正在尝试这个想法:

class NameReplacer < String    
  @@syllables = [
    {
      "Paij" => "Personal",
      "Gonk" => "Business",
      "Blon" => "Slave",
      "Stro" => "Master",
      "Wert" => "Father",
      "Onnn" => "Mother"
    },
    {
      "ree" => "AM",
      "plo" => "PM"
    }
  ]

  # method to determine what a certain name of his means
  def name_significance
    # split string by -
    parts = self.split("-")
    # make duplicate of syllables
    syllables = @@syllables.dup
    signif = parts.collect {|name| syllables.shift[name]}
    #join array returned by " " forming a string
    signif.join(" ")
  end
end

这个想法只保留前2行并删除所有其他行。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你的想法很接近。我认为这会更好:

select u.*
from (select user_id, created_datetime, 
             $num := if(@user_id = user_id, @num + 1,
                        if(@user_id := id, 1, 1)
                       ) as row_number
      from logs cross join
           (select @user_id := 0, @num := 0) params
      order by user_id 
     ) u
where row_number <= 2 ;

以下是更改:

  • 变量仅在一个表达式中设置。 MySQL不保证表达式的评估顺序,因此这很重要。
  • 工作在子查询中完成,然后在外部查询中处理。
  • 子查询使用order by,而非group by
  • 外部查询使用where代替having(实际上,在MySQL having中可行,但where更合适。)