在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

当前回答

简单的方法是:

UPDATE
    table_to_update,
    table_info
SET
    table_to_update.col1 = table_info.col1,
    table_to_update.col2 = table_info.col2

WHERE
    table_to_update.ID = table_info.ID

其他回答

UPDATE TQ
SET TQ.IsProcessed = 1, TQ.TextName = 'bla bla bla'
FROM TableQueue TQ
INNER JOIN TableComment TC ON TC.ID = TQ.TCID
WHERE TQ.IsProcessed = 0

要确保正在更新所需内容,请先选择

SELECT TQ.IsProcessed, 1 AS NewValue1, TQ.TextName, 'bla bla bla' AS NewValue2
FROM TableQueue TQ
INNER JOIN TableComment TC ON TC.ID = TQ.TCID
WHERE TQ.IsProcessed = 0
UPDATE
    Table_A
SET
    Table_A.col1 = Table_B.col1,
    Table_A.col2 = Table_B.col2
FROM
    Some_Table AS Table_A
    INNER JOIN Other_Table AS Table_B
        ON Table_A.id = Table_B.id
WHERE
    Table_A.col3 = 'cool'

像其他人一样,必须指出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上测试)

Oracle SQL(使用别名):

UPDATE Table T 
SET T.col1 = (SELECT OT.col1 WHERE OT.id = T.id),
T.col2 = (SELECT OT.col2 WHERE OT.id = T.id);

SQLite3对我很有用,在INNER SELECT之后用SELECT更新行。

UPDATE clients
SET col1 = '2023-02-02 18:51:30.826621'
FROM (
      SELECT * FROM clients dc WHERE dc.phone NOT IN (
               SELECT do.phone FROM dclient_order do WHERE do.order_date > '2023-01-01' GROUP BY do.phone
               )
      ) NewTable
WHERE clients.phone = NewTable.phone;