Question

I have two columns:

ID   name 
--------------
NULL Bose 
NULL Bose 
NULL Computer 
NULL Bose 
NULL Monitor 
NULL Monitor 
NULL Computer 
NULL Bose 
NULL Phone 
NULL Computer

Need to add unique values like this: Values should start from some number like 400.

ID name 
------------
400 Bose 
400 Bose 
401 Computer 
400 Bose 
402 Monitor 
402 Monitor 
401 Computer 
400 Bose 
403 Phone 
401 Computer 

I have tried with DISTINCT but cant figure it out, can somebody please help? Thank you!

Was it helpful?

Solution

Try this:

UPDATE  your_table s
JOIN
(SELECT (@r:=@r+1) rn, t.name FROM
(SELECT DISTINCT name FROM your_table) t
,(SELECT @r:=399) nums) tab
ON tab.name = s.name
SET s.ID = tab.rn;

Here is working code at SQL Fiddle: http://www.sqlfiddle.com/#!2/b831ed/1

OTHER TIPS

I think First you have to make the master table for above: and then update the foregin keys (IDs) against the names for the respectve PK-FK relationship.

You can do this in various ways. One method is to use variables.

update table t cross join
       (select @name := '',@prevname := '',  @id := 399) const
    set id = (case when (@prevname := @name) is null then null
                   when (@name := name) is null then null
                   when @prevname = name then @id
                   else @id := @id + 1
              end)
    order by name;

The use of the case statement is simply to allow variable assignments in the update clause.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top