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

Mysql: Update values of one column with values from multiple colums

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

新table结构:

ID | apples | bananas | cucumbers | dates

table1 个结构

ID | chiquita | grannysmith | 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)

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

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

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

你最好使用 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

UPDATE 即使您每次只想更新一列,从性能的角度来看,JOIN 是更可取的方法:

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