簡體   English   中英

MySQL根據連續行的值和條件選擇用戶ID

[英]MySQL Select User IDs based on Continuously Rows Value & condition

我有一個MySQL表

  • row_id(主要)
  • 用戶身份
  • user_ip
  • date_start(unix時間戳)
  • date_end(unix時間戳)

我想選擇只是這個表(不同)的用戶ID 如果 持續至少有2行,其中

[row X]中的user_ip與[row X + 1]中的user_ip不同

ABS([row X]中的date_end-[row X + 1]中的date_start)<= 20

行應按row_id ASC排序,以便我們可以連續獲取行X,X + 1等。

我很容易用PHP做到這一點,但是它非常慢,因此我認為只需使用sql即可完成。

row_id  |  user_id  |  user_ip   |  date_start  |  date_end

1       ,  1        ,  127.0.0.1 ,  1469100096  ,  1469100099
2       ,  2        ,  5.5.5.5   ,  1469100054  ,  1469100055
3       ,  3        ,  4.4.4.4   ,  1469100032  ,  1469100036
4       ,  1        ,  6.6.6.6   ,  1469100117  ,  1469100099
5       ,  4        ,  127.0.0.1 ,  1469100001  ,  1469100005
6       ,  2        ,  127.0.0.1 ,  1469100555  ,  1469100565

由此,我們應該只獲得用戶ID 1,因為用戶ID 1在2個連續行中具有不同的IP +第一行的date_end(1469100099)-下一行1的日期開始(469100117)= 18,即< = 20。

我們不應該返回用戶ID 2,因為盡管它驗證了第一個條件,但它沒有使用date_end和date_start驗證第二個條件。

SELECT parent.* FROM userip parent  
                JOIN userip child ON parent.`user_ip` != child.`user_ip`  
                WHERE ABS( parent.`date_end` - child.date_start) <= 20 
                      AND parent.user_id = child.user_id 
GROUP BY parent.user_id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM