在SQL Server中,可以使用insert将行插入到表中。。SELECT语句:

INSERT INTO Table (col1, col2, col3)
SELECT col1, col2, col3 
FROM other_table 
WHERE sql = 'cool'

是否也可以使用SELECT更新表?我有一个包含这些值的临时表,并希望使用这些值更新另一个表。也许是这样的:

UPDATE Table SET col1, col2
SELECT col1, col2 
FROM other_table 
WHERE sql = 'cool'
WHERE Table.id = other_table.id

当前回答

最佳实践:更新行并保存在公司使用的SQL Server中

 WITH t AS
         (
           SELECT UserID, EmailAddress, Password, Gender, DOB, Location,
           Active  FROM Facebook.Users
         )
 UPDATE t SET Active = 0

这是更新记录的最安全的方式,这是您可以看到我们将要更新的内容的方式。来源:URL

其他回答

像其他人一样,必须指出MySQL或MariaDB使用不同的语法。它还支持非常方便的USING语法(与T/SQL相反)。INNER JOIN也是JOIN的同义词。因此,原始问题中的查询最好在MySQL中实现:

UPDATE
    Some_Table AS Table_A

JOIN
    Other_Table AS Table_B USING(id)

SET
    Table_A.col1 = Table_B.col1,
    Table_A.col2 = Table_B.col2

WHERE
    Table_A.col3 = 'cool'

我在其他答案中没有看到问题的答案,因此我的两分钱。(在PHP 7.4.0 MariaDB 10.4.10上测试)

如果你想加入表本身(这不会经常发生):

update t1                    -- just reference table alias here
set t1.somevalue = t2.somevalue
from table1 t1               -- these rows will be the targets
inner join table1 t2         -- these rows will be used as source
on ..................        -- the join clause is whatever suits you

Use:

drop table uno
drop table dos

create table uno
(
    uid int,
    col1 char(1),
    col2 char(2)
)
create table dos
(
    did int,
    col1 char(1),
    col2 char(2),
    [sql] char(4)
)
insert into uno(uid) values (1)
insert into uno(uid) values (2)
insert into dos values (1,'a','b',null)
insert into dos values (2,'c','d','cool')

select * from uno 
select * from dos

或者:

update uno set col1 = (select col1 from dos where uid = did and [sql]='cool'), 
col2 = (select col2 from dos where uid = did and [sql]='cool')

OR:

update uno set col1=d.col1,col2=d.col2 from uno 
inner join dos d on uid=did where [sql]='cool'

select * from uno 
select * from dos

如果两个表中的ID列名相同,则只需将表名放在要更新的表之前,并为所选表使用别名,即:

update uno set col1 = (select col1 from dos d where uno.[id] = d.[id] and [sql]='cool'),
col2  = (select col2 from dos d where uno.[id] = d.[id] and [sql]='cool')

SQL数据库中使用INNER JOIN从SELECT进行UPDATE

由于这篇文章的回复太多了,投票最多,我想我也会在这里提供我的建议。虽然这个问题很有趣,但我在许多论坛网站上看到过,并使用INNER JOIN和截屏制作了一个解决方案。

首先,我创建了一个名为schoolold的表,并插入了一些与列名相关的记录并执行它。

然后我执行SELECT命令来查看插入的记录。

然后我创建了一个名为schoolnew的新表,并对其执行了类似的上述操作。

然后,为了查看其中插入的记录,我执行SELECT命令。

现在,我想对第三行和第四行进行一些更改,为了完成此操作,我使用INNER JOIN执行UPDATE命令。

要查看更改,我执行SELECT命令。

通过使用INNER JOIN with UPDATE语句,您可以看到表schoolold的第三和第四记录如何容易地替换为表schoolnew。

这样地;但是您必须确保更新表和from之后的表是相同的。

UPDATE Table SET col1, col2
FROM table
inner join other_table Table.id = other_table.id
WHERE sql = 'cool'