在MySQL中,我們經常需要查詢某張表的前后五條數據,這里介紹幾種實現的方法。
一、使用LIMIT和OFFSET
SELECT * FROM table_name ORDER BY id DESC LIMIT 5 OFFSET 5; -- 取得后五條數據 SELECT * FROM table_name ORDER BY id ASC LIMIT 5; -- 取得前五條數據
二、使用子查詢和ORDER BY
-- 取得前五條數據 SELECT * FROM ( SELECT * FROM table_name ORDER BY id DESC LIMIT 5 ) AS t ORDER BY id ASC; -- 取得后五條數據 SELECT * FROM ( SELECT * FROM table_name ORDER BY id ASC LIMIT 5 ) AS t ORDER BY id DESC;
三、使用UNION ALL
-- 取得前后各五條數據 (SELECT * FROM table_name ORDER BY id DESC LIMIT 5) UNION ALL (SELECT * FROM table_name ORDER BY id ASC LIMIT 5);
四、使用ROW_NUMBER()函數
-- 取得前五條數據 SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY id ASC) AS rn FROM table_name ) AS t WHERE rn<= 5; -- 取得后五條數據 SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY id DESC) AS rn FROM table_name ) AS t WHERE rn<= 5;
上一篇excel轉換成json
下一篇css3 3d教學ppt