Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add integer column to an existing mysql table based on existing column

Tags:

mysql

I want to add a new column to an existing mysql table, where the new column is a unique integer number for each unique value of an existing column in the table. For example, if the existing column has unique values A and B (and there might be 50 rows of each of A and B), then add a new column with values of 1 and 2 in each row where there is an A and B, respectively.

like image 615
sckott Avatar asked Dec 16 '11 17:12

sckott


1 Answers

well, it require two commands

ALTER TABLE your_table ADD COLUMN your_column INTEGER UNIQUE;

And then for each column record, you create an update statements to do so, like:

UPDATE your_table SET your_column = 1 WHERE column = 'A'
UPDATE your_table SET your_column = 2 WHERE column = 'B'

Or you create a procedure for that, if the records are many.

like image 102
Anderson Carniel Avatar answered Nov 11 '22 12:11

Anderson Carniel