如果字段为空,则仅从select语句更新查询

时间:2014-05-07 20:35:39

标签: sql sql-update

我正在尝试编写一个sql语句来从另一个表列更新表的列。但是我只想更新列,如果它是空的。

例如:

UPDATE
    Table
SET
    Table.col1 = other_table.col1,
FROM
    Table
INNER JOIN
    other_table
ON
    Table.id = other_table.id

但我想仅在该值为空时才设置Table.col1值。什么是最好的方法呢?

1 个答案:

答案 0 :(得分:4)

定义空?

但实际上你只需要一个像

这样的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

在Postgre中,您可能需要不同的语法(How to do an update + join in 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
相关问题