sho
sho

Reputation: 761

SQL... How to update rows with data from other rows in the same table?

I'm using MySQL server and I have a table where some rows are missing data. I would like to update the rows using information from other rows. My table looks something like:

id,signin,deviceId,deviceModel
1,2010-10-12,9ABC9,
2,2010-10-12,3E44F,
3,2010-10-13,D3453,
4,2010-10-14,D3453,
5,2010-10-14,D3453,HW1
6,2010-10-12,3E44F,HW2
7,2010-10-12,9ABC9,HW1

For the first few entries, the deviceModel field is empty. I would like to update this value using the deviceModel found for the deviceId in other rows of this same table. In the example above, row 1 should have deviceModel = HW1, row 2 should have deviceModel = HW2, etc.

Thanks!

Upvotes: 3

Views: 2109

Answers (2)

Vishal
Vishal

Reputation: 12369

Self Join -

UPDATE MyTable m1, MyTable m2 
SET m1.deviceModel= m2.deviceModel
WHERE m1.deviceid=m2.deviceid and m2.deviceModel is not null

Upvotes: 2

Mchl
Mchl

Reputation: 62387

First of all, this is a denormalised design. You should move deviceModel -> deviceId relation to another table.

Second:

UPDATE
  yourTable AS t1
CROSS JOIN (
  SELECT DISTINCT 
    deviceId, deviceModel 
  FROM 
    yourTable 
  WHERE 
    deviceModel IS NOT NULL
) AS t2
USING (deviceId)
SET
  t1.deviceModel = t2.deviceModel
WHERE
  t1.deviceModel IS NULL

Upvotes: 3

Related Questions