mysql 查詢各個狀態的最新的3條記錄


先創建表

CREATE TABLE test(
    id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    status INT(11),
    value VARCHAR(20)
);

寫入部分數據

INSERT INTO test(status,value) VALUES
(1,'測試1'),
(2,'測試2'),
(3,'測試3'),
(1,'測試4'),
(2,'測試5'),
(3,'測試6'),
(2,'測試7'),
(2,'測試8'),
(4,'測試9'),
(1,'測試10');

 

1、既然是查詢各個狀態那么就需要用到分組(group by)來實現

select * from test group by status

此時發現查詢出來的數據每個狀態只有一條而且不是最新的
2、再添加排序(order by)和限制(limit)發現沒有達到預期效果

select * from test group by status order by id DESC limit 3

3、想想篩選有關的還有一個having函數,這個函數可以處理篩選分組之后的數據

4、將test表和自身進行leftjoin,可以找到每條狀態數據中id大於自身的數量,通過這個數量的篩選來進行最新的篩選,此時分組的條件也需要修改下

select a.id,a.status,a.value,count(b.id) from test as a LEFT JOIN test b on b.status = a.status and b.id > a.id group by a.id,a.status,a.value

這樣就能查詢出,每條數據相同狀態下ID大於自身的數量,根據這個數量的篩選就能查詢出最新的數據

5、使用having函數篩選分組后的數據

select a.id,a.status,a.value,count(b.id) as count from test as a LEFT JOIN test b on b.status = a.status and b.id > a.id group by a.id,a.status,a.value having count < 3

此時查詢出來的數據就是每個狀態中最新的三條記錄
6、還可以再加上order by來對數據進行進一步的排序

select a.id,a.status,a.value,count(b.id) as count from test as a LEFT JOIN test b on b.status = a.status and b.id > a.id group by a.id,a.status,a.value having count < 3 ORDER BY a.status DESC, a.id DESC


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM