如何插入来自另一个 table 的更新数据?

How to do INSERT INTO updated data from another table?

我有一个新的 table(称为“NewTable”),它是使用来自 2 tables(t1 和 t2)的数据创建的。我正在尝试将 t1 和 t2 中的任何新数据插入到“NewTable”中。请看下面的例子。

新表:

id | col1 | col2 | col3 | col4 |

t1:

id | col1 | col2 | col5 | col6 |

t2:

id | col3 | col4 | col7 | col8 |

我的脚本是:

INSERT NewTable (id, col1, col2, col3, col4)
SELECT t1.d1, col1, col2, col3, col4
FROM NewTable left join t1 on NewTable.id = t1.id left join t2 on t1.id=t2.id
WHERE t1.id is NULL;

我收到这条错误消息

Cannot insert the value NULL into column 'id', table 'New Table'; column does not allow nulls. INSERT fails.

我觉得我的剧本不对劲。我应该使用右连接而不是左连接,还是应该使用“WHERE NewTable is NULL”代替?

感谢您的帮助

如果您想从 t1t2 中插入 NewTable 行,并且 id 中不存在 NewTable,那么您必须使用 INNER 加入 t1t2,然后 LEFT 加入 NewTable 和 return 不匹配的行:

INSERT INTO NewTable (id, col1, col2, col3, col4)
SELECT t1.id, t1.col1, t1.col2, t2.col3, t2.col4
FROM t1 INNER JOIN t2 ON t2.id = t1.id
LEFT JOIN NewTable ON NewTable.id = t1.id
WHERE NewTable.id IS NULL;