Mysql查詢連續數據

查詢連續記錄並對這些連續數據統計取出指定連續次數的記錄,這類操做並很少,但出現時會比較棘手。mysql


查詢思想是:sql

順序行號 - 減首差值 = 連續差塊 微信


順序行號 如同 oracle 中的 rownum 但mysql目前尚未這個功能,因此只能經過局部變量來實現,oracle

減首差值 就是每條記錄與最開始記錄的差(須要保證這個差值與順序行號遞增值相同,固然若是原本就是自增值則不須要單獨計算)ide


只要 順序行號與減首差值保持相同遞增值則 連續差塊 值相同,就能夠統計出連續長度函數



示例表:(以簡單的簽到表爲例)fetch

create table user_sign(
id int unsigned primary key auto_increment,
user_id int unsigned not null comment '用戶ID',
date date not null comment '簽到日期',
created_time int unsigned not null comment '建立時間',
updated_time int unsigned not null comment '修改時間'
)engine=innodb default charset=utf8 comment '用戶簽到';

隨機生成數據(建立函數隨機生成簽到數據)
spa

create function insert_sign_data(num int)
returns int
begin
declare _num int default 0;
declare _date date;
declare _tmpdate date;
declare _user_id int;
declare line int default 0;
declare _get_last cursor for select date from user_sign where user_id=_user_id order by date desc limit 1;
declare continue handler for SQLSTATE '02000' set line = 1;
while _num < num do
set _user_id = CEIL( RAND( ) * 500 );
open _get_last;
fetch _get_last into _tmpdate;
IF line THEN
set _date = FROM_UNIXTIME( unix_timestamp( ) - 86400 * round( RAND( ) * 200 ), '%Y-%m-%d' );
set line = 0;
ELSE
set _date = FROM_UNIXTIME( unix_timestamp( _tmpdate ) + 86400 * round( RAND( ) * 2 + 1), '%Y-%m-%d' );
END IF;
INSERT INTO user_sign ( user_id, date, created_time, updated_time ) VALUES (_user_id, _date, unix_timestamp( ), unix_timestamp( ));
set _num = _num + 1;
close _get_last;
end while;
return _num;
end

生成數據(因爲生成時有判斷最近打卡日期生成有會點慢)unix

select insert_sign_data(20000);


提取出連續打卡超過6天的用戶orm

SELECT
user_id,
val - ( @rownum := @rownum + 1 ) AS type,
group_concat( date ) AS date_join,
count( 1 ) num 
FROM
(
SELECT
us1.date,
us1.user_id,
( unix_timestamp( us1.date ) - min_timestamp ) / 86400 + 1 AS val 
FROM
user_sign AS us1
LEFT JOIN ( SELECT UNIX_TIMESTAMP( min( date ) ) AS min_timestamp, user_id, min( date ) AS min_date FROM user_sign GROUP BY user_id ) AS us2 ON us1.user_id = us2.user_id 
ORDER BY
us1.user_id ASC,
us1.date ASC 
) AS t1,
( SELECT @rownum := 0 ) AS t2 
GROUP BY
user_id,
type 
HAVING
num > 6


這裏查詢的是全表裏連續超過3次打卡的,並把日期展現出來。

查詢的思路是:

  1. 提取出全表用戶每次打卡記錄與第一次打卡記錄的差值但按用戶與日期正排序

  2. 增長一個局部變量rownum與上面查詢數據進行連查

  3. 在結果字段集裏使用日期差值減去自增順序行號值獲得連續差塊

  4. 經過分組用戶與連續差塊獲取連續簽到次數

  5. 經過having來提取超過6次簽到的用戶


微信截圖_20180927180520.png

相關文章
相關標籤/搜索