我想根据我table1 name
table2 name
table1
中table2
的引用,将id
与insert into table1 (name)
select name from table2
where table2.id = table1.table2Id;
一起投放。
我怎样才能做到这一点?类似的东西:
where
table1
子句不知道col-sm-10
并且无法应用该条件。
答案 0 :(得分:1)
您可以在INSERT..SELECT查询中使用FROM子句(使用JOIN),也可以在UPDATE和/或DELETE查询中使用。
如果要根据table2中的数据将新记录插入到table1中,您可能只需要确保不会尝试在table1中插入可能会破坏任何约束的数据。
在这种情况下,示例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
如果要使用table2中的数据更新table1中的现有记录,则可以使用UPDATE查询而不是INSERT查询。同样,您应该检查是否不会尝试更新会破坏任何约束的数据。
更新table1中与table2中的数据匹配的记录的示例:
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子句中提供与目标表记录的正确连接。