【问题标题】:update query from select statement only update if the field is empty仅当字段为空时才更新来自 select 语句的查询
【发布时间】:2014-06-25 00:35:55
【问题描述】:

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

例如:

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

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

【问题讨论】:

  • where Table.col1 is null ?取决于你的意思是空......

标签: sql sql-update


【解决方案1】:

定义为空?

但实际上你只需要一个 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

【讨论】:

  • 利用@KarlKieninger 的声明,空条目和空条目(即'')之间存在主要区别。
  • 为什么会抛出“table name Table spcecified more than once -> here Table is my table name.
  • @Null-Hypothesis 因为您在更新语句中进行了联接。这可以解决(但通常在 dbms 之间有所不同)。那么你的 dbms 是什么?
  • @RaphaëlAlthaus 我正在使用 postgres
  • 哦,在 postgre 中是不同的。您需要稍微更改连接语法,但您的 aander 仍然需要添加适当的 where 空条件。见stackoverflow.com/questions/7869592/…
猜你喜欢
  • 1970-01-01
  • 2017-02-27
  • 1970-01-01
  • 1970-01-01
  • 2012-06-14
  • 2018-04-19
  • 2011-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多