SELECT user_id, date_time, journal_id FROM logs WHERE user_id = 1
user_id | date_time | journal_id
1 | 2014-02-04 11:15:00 | 21
1 | 2014-02-04 11:25:00 | 22
1 | 2014-02-04 14:00:00 | 31
1 | 2014-02-05 10:15:00 | 33
1 | 2014-02-05 12:55:00 | 45
1 | 2014-02-05 15:15:00 | 48
1 | 2014-02-05 15:35:00 | 49
1 | 2014-02-06 05:00:00 | 62
1 | 2014-02-06 13:40:00 | 67
1 | 2014-02-06 15:00:00 | 72
我想为每个日期选择前3行(*注意,feb。的第5行有4行),我在想它是否可以计数或限制,但没有任何运气。 我一直在寻找解决方案,但没有运气。大多数情况下,我真的想知道它是否可以与MySQL一起使用,或者我只需要在PHP中进行一些日期检查,从结果中删除不需要的行。
我的目标实际结果是:
user_id | date_time | journal_id
1 | 2014-02-04 11:15:00 | 21
1 | 2014-02-04 11:25:00 | 22
1 | 2014-02-04 14:00:00 | 31
1 | 2014-02-05 10:15:00 | 33
1 | 2014-02-05 12:55:00 | 45
1 | 2014-02-05 15:15:00 | 48
1 | 2014-02-06 05:00:00 | 62
1 | 2014-02-06 13:40:00 | 67
1 | 2014-02-06 15:00:00 | 72
有什么想法吗?
答案 0 :(得分:1)
工作解决方案:
select user_id, date_time, journal_id from (
select
user_id, date_time, journal_id
, @crid:=
(case when @pdt=(@cdt:=date_format(date_time, '%Y-%m-%d'))
then (@crid+1)
else (@pdt:=@cdt)/@pdt
end) as grouped_row_num
from logs, ( select @crid:=0, @cdt:=0, @pdt:=0 ) r
) results
where grouped_row_num <= 3
;
答案 1 :(得分:0)
答案 2 :(得分:0)
您可能需要尝试以下
我将如何制作它的一个例子:
CREATE PROCEDURE SHOW_FIRS_ROWS (IN TABLENAME VARCHAR(50))<br/>
DECLARE varSQL VARCHAR(255);
DECLARE varDATE VARCHAR(100);
DECLARE no_more_rows INT DEFAULT 0;
DECLARE cursor1 CURSOR FOR SELECT DISTINCT DATE(date_time) FROM logs;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = 1;
OPEN cursor1;
FETCH cursor1 INTO varDATE;<br/>
REPEAT
SET @varSQL = CONCAT("INSERT INTO newTable SELECT * FROM logs WHERE DATE(date_time) = ", varDATE ," LIMIT 0,3");<br/>
PREPARE stmt FROM @varSQL;<br/>
EXECUTE stmt;<br/>
FETCH cursor1 INTO varDIR;<br/>
UNTIL no_more_rows = 1 END REPEAT;<br/>
CLOSE cursor1;<br/>
END