Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Auto increment temporary column in select statement

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 =@cnt + 1) AS rowNumber,     rowID FROM myTable WHERE CategoryID = 1 

Which returns:

+++++++++++++++++++++ + rowNumber | rowID + +++++++++++++++++++++ +  (NULL)   |   1   + +  (NULL)   |   25  + +  (NULL)   |   33  + +  (NULL)   |   150 + +  (NULL)   |   219 + +++++++++++++++++++++ 

But I need:

+++++++++++++++++++++ + rowNumber | rowID + +++++++++++++++++++++ +  1        |   1   + +  2        |   25  + +  3        |   33  + +  4        |   150 + +  ...      |   ... + +++++++++++++++++++++ 
like image 700
Sg1456 Avatar asked Apr 10 '13 15:04

Sg1456


People also ask

How can create auto increment column in MySQL query?

In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name.

How do you increment a variable in SQL SELECT statement?

set @anyVariableName=0; select yourColumnName, @anyVariableName:=@anyVariableName+1 as anyVariableName from yourTableName; To understand the above syntax and set an increment counter, let us first create a table. The query to create a table is as follows. Insert some records in the table using insert command.

How can create auto increment serial number in SQL?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .


2 Answers

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 |
like image 194
Kermit Avatar answered Oct 08 '22 19:10

Kermit


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 
like image 20
Arrabi Avatar answered Oct 08 '22 20:10

Arrabi