如何从另一个表插入更新的数据?

5us2dqdw  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(266)

我有一个新表(称为“newtable”),它是用两个表(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”?
谢谢你的帮助

ehxuflar

ehxuflar1#

如果要插入 NewTable 中的行 t1 以及 t2 同样的 id 在这个世界上还不存在 NewTable 那么你必须加入一个 INNER 加入 t1 以及 t2 ,那么 LEFT 加入 NewTable 并返回不匹配的行:

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;

相关问题