You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL中按行号查询指定行数据的正确语法实现

How to Fetch a Specific Row by Row Number in MySQL

Got it, let's work through this MySQL row number issue you're hitting. The problem with your original attempts is that window functions like ROW_NUMBER() can't be used directly in the WHERE clause—MySQL runs the WHERE filter before applying window functions, so those conditions don't behave as you'd expect.

Here are two reliable, straightforward ways to get the specific row you need:

1. Use a Subquery/CTE to Calculate Row Numbers First

Wrap the row number calculation in a subquery (or CTE, if you're on MySQL 8.0+) so you can filter on the computed row number in the outer query.

With CTE (MySQL 8.0+)

This is cleaner and easier to read:

WITH numbered_rows AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY REFNUM) AS row_num
    FROM MYTABLE
)
SELECT * FROM numbered_rows WHERE row_num = 2;

With Subquery (Works for Older MySQL Versions)

If you're stuck on a version before 8.0, use a subquery instead:

SELECT *
FROM (
    SELECT *, ROW_NUMBER() OVER (ORDER BY REFNUM) AS row_num
    FROM MYTABLE
) AS sub_query
WHERE sub_query.row_num = 2;

2. Use LIMIT + OFFSET (Simpler for Single Rows)

If you just need to fetch the Nth row and don't require the explicit row number value, this method is more concise. Critical note: Always include ORDER BY—without it, MySQL doesn't guarantee a consistent row order, so your "2nd row" might change randomly between queries.

SELECT * FROM MYTABLE ORDER BY REFNUM LIMIT 1 OFFSET 1;
  • LIMIT 1 tells MySQL to return only 1 row
  • OFFSET 1 skips the first row, so you get the 2nd one (adjust the offset for other rows: e.g., OFFSET 4 for the 5th row)

Key Reminder

Never skip the ORDER BY clause! MySQL tables don't have a fixed "natural" order. Without sorting, the row you retrieve could be arbitrary, depending on how data is stored or cached.

内容的提问来源于stack exchange,提问作者TSG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 14:27:36