Mysql:使用多个列的值更新一列的值

时间:2015-10-20 15:27:39

标签: mysql sql mariadb

我的数据库中有大约12个表,列数很多。我想从他们那里选择我需要的信息并将其放入具有预定义结构的新表中。所有表都有唯一标识符“ID”。

newtable结构:

  

ID |苹果|香蕉|黄瓜|日期

table1结构

  

ID | chiquita |格兰尼史密斯IDontWanthis | OrThis

使用:

UPDATE newtable SET bananas = (SELECT chiquita FROM table1
                               WHERE newtable.ID = table1.ID)

但是,当更多列可以保存我需要填写新列的信息时,我遇到了困难。

我试过了:

UPDATE newtable SET apples = (SELECT grannysmith FROM table1
                              WHERE newtable.ID = table1.ID)

然后是新的更新:

UPDATE newtable SET apples = (SELECT elstar FROM table2
                              WHERE newtable.ID = table2.ID
                              AND newtable.apples IS NULL)

然而,它用table2.elstar替换newtable.apples中的所有值,而不仅仅是NULL值。之前填充的值现在为NULL。

我对SQL很新,不知道我做错了什么。 有没有更有效的方法来做到这一点? 感谢您的支持!

2 个答案:

答案 0 :(得分:1)

UPDATE newtable SET apples = (SELECT elstar FROM table2
                          WHERE newtable.ID = table2.ID
                          AND newtable.apples IS NULL)
WHERE apples IS NULL

您还需要where子句来过滤外部查询中的apples is null

答案 1 :(得分:0)

您最好使用JOIN

http://sqlfiddle.com/#!9/f3dda/1

UPDATE newtable n
INNER JOIN table1 t
ON n.id = t.id
SET n.bananas = t.chiquita, n.apples = t.grannysmith

如果您想避免在newtable中覆盖旧值,则可以更改ON子句,如:

UPDATE newtable n
INNER JOIN table1 t
ON n.id = t.id AND (n.bananas IS NULL OR n.apples IS NULL)
SET n.bananas = t.chiquita, n.apples = t.grannysmith

更新即使您每次只想更新一列JOIN,从绩效角度来看,这是更优选的方式:

UPDATE newtable n
INNER JOIN table1 t
ON n.id = t.id AND n.bananas IS NULL 
SET n.bananas = t.chiquita