简体   繁体   English

在MySQL中使用LIMIT时如何轻松获取行号?

[英]How to easily get row number when using LIMIT in MySQL?

Suppose I have a database table with quite a few rows which I want to display to an user. 假设我有一个数据库表,其中有很多行要显示给用户。 It would make sense to LIMIT the output, and make pages of rows. 限制输出并创建行页面是有意义的。 In MySQL I would do this: 在MySQL中,我可以这样做:

SELECT * FROM myTable ORDER BY myValue LIMIT 120,10

which will show 10 rows starting from row 120. So MySQL must use, internally, some kind of order, and has numbered the rows accordingly. 它将显示从第120行开始的10行。因此,MySQL必须在内部使用某种顺序,并已对行进行了相应编号。 I would like to display the row number with each row. 我想显示每一行的行号。 How do I get access to these numbers, using only MySQL? 我如何仅使用MySQL来访问这些号码? To be clear, I am looking for something like this: 要清楚,我正在寻找这样的东西:

SELECT *,<LIMIT_ROWNO> FROM myTable ORDER BY myValue LIMIT 120,10

I looked online and in the manual, but I cannot find it. 我在网上和手册中进行了查找,但找不到。 I would prefer something simple, without using variables, or functions. 我更喜欢简单的东西,而不使用变量或函数。 Isn't there a predefined expression for this? 没有为此预定义的表达式吗?

I can solve this problem easily in PHP, but it would be more logical to get the row numbers from MySQL. 我可以在PHP中轻松解决此问题,但是从MySQL获取行号会更合乎逻辑。

You can't do it without using variables, eg: 不使用变量就无法做到这一点,例如:

SELECT m.*, @rownum := @rownum + 1 as `num`
FROM myTable m, (SELECT @rownum := 120) a 
ORDER BY myValue LIMIT 120,10;
set @rownum=120;
SELECT *,@rownum:=@rownum+1 as rn FROM myTable ORDER BY myValue LIMIT 120,10; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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