从选择语句更新查询仅在字段为空时更新

add*_*ons 2 sql sql-update

我试图写一条sql语句从另一个表列更新一个表的列。但是我只想更新该列为空。

例如:

UPDATE
    Table
SET
    Table.col1 = other_table.col1,
FROM
    Table
INNER JOIN
    other_table
ON
    Table.id = other_table.id
Run Code Online (Sandbox Code Playgroud)

但是我只想设置Table.col1值为空。最好的方法是什么?

Kar*_*ger 5

定义为空?

但实际上您只需要一个WHERE子句,例如

UPDATE Table
   SET Table.col1 = other_table.col1,
  FROM Table
       INNER JOIN
       other_table ON Table.id = other_table.id
 WHERE Table.col IS NULL  --or whatever your empty condition is
Run Code Online (Sandbox Code Playgroud)

在Postgre中,您可能需要使用其他语法(如何在PostgreSQL中进行更新和联接?):

UPDATE Table
   SET Table.col1 = other_table.col1,
  FROM Table
      ,other_table 
 WHERE Table.id = other_table.id
   AND Table.col IS NULL  --or whatever your empty condition is
Run Code Online (Sandbox Code Playgroud)