Reputation: 2461
I want to add a new column to one table with default value from other table's column.
1st Table 'sensors'
-------------------------------------------------------------
id sensorId location city country userId
-------------------------------------------------------------
2nd Table sensordata
-------------------------------
id sensorId dataValues
-------------------------------
I want to add a column in the sensordata table with the default value of location where sensorId is same.
How can I do that?
Something like this
ALTER TABLE `sensordata` s ADD `location` VARCHAR( 200 ) NOT NULL DEFAULT
(SELECT location from sensors s WHERE s.sensorId = d.sensorId) AFTER `dataValues`
Please don't tell me why I need to have duplicate data, there is a reason for that :)
Upvotes: 2
Views: 164
Reputation: 44844
You need to do it in 2 steps
step1
ALTER TABLE `sensordata` ADD `location` VARCHAR( 200 ) ;
step2
update sensordata sd
join sensors s on s.sensorId = sd.sensorId
set sd.location = s.location
Updated: This is what I have done and it works fine
ALTER TABLE `sensordata` ADD `location` VARCHAR(200) NULL DEFAULT NULL AFTER `dataValues`;
UPDATE sensordata d SET d.location = (SELECT s.location from sensors s WHERE s.sensorID = d.sensorID);
Upvotes: 2
Reputation: 37364
Mysql requires default value to be a constant in almost all cases - https://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html .
You can write before insert
trigger though to emulate DEFAULT
functionality to some extent. Surely, trigger will affect only new rows, and you will need to manually update existing.
Upvotes: 1