色婷婷狠狠18禁久久YY,CHINESE性内射高清国产,国产女人18毛片水真多1,国产AV在线观看

mysql取前后五條

江奕云1年前9瀏覽0評論

在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;