MySQL: Auto increment temporary column in select statement

前端 未结 3 1329
名媛妹妹
名媛妹妹 2020-12-07 12:27

How do I create and auto increment a temporary column in my select statement with MySQL?

Here is what I have so far:

SET @cnt = 0;
SELECT
    (@cnt          


        
3条回答
  •  余生分开走
    2020-12-07 13:29

    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
    

提交回复
热议问题