gpt4 book ai didi

sql - insert into from where 两个表的条​​件

转载 作者:行者123 更新时间:2023-11-29 13:14:51 24 4
gpt4 key购买 nike

我要喂table1 nametable2 name基于我对 table1 的引用在我的 table2 (id)。

我怎样才能做到这一点?像这样的东西:

insert into table1 (name)
select name from table2
where table2.id = table1.table2Id;

where子句不知道table1并且不能应用该条件。

最佳答案

您可以在 INSERT..SELECT 查询中使用 FROM 子句(带有 JOIN),但也可以在 UPDATE 和/或 DELETE 查询中使用。

如果您想根据表 2 中的数据向表 1 中插入新记录,您可能只需要确保不会尝试向表 1 中插入可能会破坏任何约束的数据。

您的示例 INSERT 查询中的 WHERE 子句在那种情况下可能无效,因为它似乎假设 table1 中已经有匹配的记录。 (可能存在证明此类查询合理的特殊情况,但我不会在这里详细说明这些情况,因为您的问题并未表明这与您的情况相关。)

根据table1和table2中的(相关)数据在table1中插入记录的示例:

INSERT INTO table1 (name)
SELECT table2.name
FROM table2 JOIN table1 ON table1.[ref] = table2.[ref] --use some sensible relation logic between table1 and table2 here
WHERE ... --check for valid data here

如果您想用表 2 中的数据更新表 1 中的现有记录,您可以使用 UPDATE 查询而不是 INSERT 查询。同样,您应该检查您是否尝试更新会破坏任何约束的数据。

更新表 1 中与表 2 中的数据匹配的记录的示例:

UPDATE table1
SET name = table2.name
FROM table2
WHERE table2.id = table1.id --or use some other sensible relation logic between table1 and table2 here (together with other validation logic)

您也可以在 UPDATE 查询中使用 FROM 子句,但似乎您必须小心不要在该 FROM 子句中包含目标表,并在 WHERE 子句中提供与目标表记录的正确连接。

关于sql - insert into from where 两个表的条​​件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50409358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com