Home >Database >Mysql Tutorial >How to Assign Sequential Numbers to Table Columns in MySQL?
Assigning Sequential Numbers to Table Columns in MySQL
Suppose you have a MySQL table with columns named 'Name' and 'Number', where the 'Number' column currently contains null values. The goal is to assign sequential numbers starting from 1 to the 'Number' column for each row in the table. This could be achieved using the following SQL command:
SET @rank:=0; update T set Number=@rank:=@rank+1;
Explanation:
Alternative Method:
Alternatively, you can use a single SQL statement with a subquery:
UPDATE T JOIN (SELECT @rank := 0) r SET Number=@rank:=@rank+1;
Note:
For tables with a large number of rows, it is advisable to create an additional column with the AUTO_INCREMENT attribute instead of relying on user-defined variables or subqueries.
The above is the detailed content of How to Assign Sequential Numbers to Table Columns in MySQL?. For more information, please follow other related articles on the PHP Chinese website!