標籤:
現在有個有意思的狀況,在使用者登入成功的時候 ,要顯示使用者上一次登入的資訊,時間和IP等。可是在使用者登入資訊表中,並不會記錄使用者的登入過程,只記錄的帳號密碼這些基礎資訊,使用者的操作全部記錄在日誌表中。
還有,在使用者登入成功的時候,會自動想日誌表中添加一條記錄,在前兩天的觸發器部分已經解決了這個問題。那麼,我們需要做三件事:
1:在log表中找到該使用者的所有登入記錄
2:按照時間降序排序
3:找到第二行記錄,並返回。
為什麼是第二行,因為第一行是使用者當前登入的資訊,第二行才是上次登入的資訊。
先建立簡單的日誌表,時間還是用timestamp類型,不需要自己進行添加。content儲存操作類型,比如說 login logout
create table log( id int not null primary key auto_increment, operationTime timestamp, content varchar(20), user_id int )
插入記錄,我並沒有一次全部插入,操作之間是有時間分隔的。
insert into log(content,user_id) values(‘login‘,2);insert into log(content,user_id) values(‘login‘,4);insert into log(content,user_id) values(‘logout‘,4);insert into log(content,user_id) values(‘logout‘,2);insert into log(content,user_id) values(‘login‘,2);insert into log(content,user_id) values(‘logout‘,2);insert into log(content,user_id) values(‘login‘,2);
通過上表我們能看到,使用者2 登入 登出 登入 登出 然後再登入。假設最後一次登入是使用者2正在執行的操作,我們要顯示上一次的登入資訊,就必須把id為5的內容擷取到。看到這我們發現,可以不對時間進行排序,對id進行排序也是可以的。
1:分組 group by
我們能看到,是通過user_id分成了兩組,每組都顯示分組後的第一條記錄,顯然這個是滿足不了我們的需求的。我們需要得到user_id=2這組的所有內容。
2:where字句
其實用不到分組,我們可以通過where字句來擷取具體的內容。
where ··· and ··· 我們就能得到使用者2的所有login操作的內容了。
3:排序 order by
desc 是降序 asc是升序。文法也很簡單。
現在我們得到了如上的內容,接下來需要得到第二行記錄。
4:限定 limit
報錯了,說table要有別名。那給table加上個別名看看。
終於如願以償的得到第二行記錄了。再看看我們輸入了什麼命令
select * from (select * from log as l where l.user_id=2 and l.content=‘login‘ order by id desc) as lo limit 1,1;
(select * from log as l where l.user_id=2 and l.content=‘login‘ order by id desc)是得到了一個表,然後我們在這個表的基礎上再進行查詢。
limit n,m 是說從 0開始,找到n 到 m之間的記錄。我們只需要第二條記錄,所以是limit 1,1。
mysql 分組+排序+限定