MySQL: Auto increment temporary column in select statement

ぃ、小莉子 提交于 2019-11-28 03:56:30
Kermit

This will give you a consecutive row number with 3.

SELECT
    (@cnt := @cnt + 1) AS rowNumber,
    t.rowID
FROM myTable AS t
  CROSS JOIN (SELECT @cnt := 0) AS dummy
WHERE t.CategoryID = 1
ORDER BY t.rowID ;

Result

| ROWNUMBER | ROWID |
---------------------
|         1 |     1 |
|         2 |    25 |
|         3 |    33 |
|         4 |   150 |

Try this:

SET @rownr=0;
SELECT @rownr:=@rownr+1 AS rowNumber, rowID
  FROM myTable
  WHERE CategoryID = 1

In modern versions of MySQL you can use MySQL Window: http://www.mysqltutorial.org/mysql-window-functions/mysql-row_number-function/

Example:

SELECT  ROW_NUMBER() OVER (  ORDER BY productName  ) row_num, 
        productName, msrp 
FROM   products ORDER BY   productName;
Arrabi

But what if you have a group by in the select statement? the counting will be off.

For such cases, the only solution I found is nesting select:

SELECT (@cnt := @cnt + 1) AS rowNumber, t.*
from
(select
    t.rowID
FROM myTable 
WHERE CategoryID = 1
ORDER BY rowID) t
CROSS JOIN (SELECT @cnt := 0) AS dummy
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!