简体   繁体   中英

Select the second last row in Mysql

I've been trying to get the second last row of data on mysql. But my query only shows the last row.

SELECT news.news_title, news.news_details, news.news_author, news_images.filename
FROM news JOIN news_images 
ON news.news_title = news_images.news_title 
ORDER BY news_id DESC LIMIT 1

Use OFFSET to get second last value like:

SELECT news.news_title, news.news_details, news.news_author, news_images.filename
FROM news JOIN news_images 
ON news.news_title = news_images.news_title 
ORDER BY news_id DESC
LIMIT 1 OFFSET 1;

LIMIT number_of_rows OFFSET start_from

If you want 2 last rows use: LIMIT 2 .

EDIT: Your question is very unclear but try:

SELECT t.news_title, t.news_details, t.news_author, ni.filename
FROM (SELECT news_title, news_details, news_author
      FROM news
      ORDER BY news_id DESC
      LIMIT 1 OFFSET 1) AS t
JOIN news_images ni
  ON t.news_title = ni.news_title 
SELECT news.news_title, news.news_details, news.news_author, news_images.filename
FROM news JOIN news_images 
ON news.news_title = news_images.news_title 
ORDER BY news_id DESC
LIMIT 1 OFFSET 1;

You should also refer Select the nth Highest Record in a Database Table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM