基本上我需要为每个用户只获取最后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行并删除所有其他行。
有什么想法吗?
答案 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 ;
以下是更改:
order by
,而非group by
。where
代替having
(实际上,在MySQL having
中可行,但where
更合适。)