简体   繁体   English

MySQL:将新列插入到具有其他表默认值的表中

[英]MySQL: insert new column into a table with default value from other table

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. 我想在sensordata表中添加一列,其默认值是sensorId相同的位置。

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 :) 请不要告诉我为什么我需要重复数据,这是有原因的:)

You need to do it in 2 steps 您需要2个步骤

step1 第1步

ALTER TABLE  `sensordata`  ADD  `location` VARCHAR( 200 )  ;

step2 第2步

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);

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 . Mysql在几乎所有情况下都要求默认值是一个常量-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. 您可以before insert触发器before insert编写代码before insert尽管可以before insert某种程度上模拟DEFAULT功能。 Surely, trigger will affect only new rows, and you will need to manually update existing. 当然,触发器将仅影响新行,并且您将需要手动更新现有行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM