【问题标题】:Updating column in table using left join from another table in SQL使用 SQL 中另一个表的左连接更新表中的列
【发布时间】:2021-12-22 05:32:34
【问题描述】:

我想更新“location_costs”表下“animals”表基础成本下的“location_cost”列。主键是连接两个表的位置。我尝试了以下代码,但它给了我语法错误。

//UPDATE animals.* 
SET animals.location_cost = location_costs.costs
FROM animals       
LEFT JOIN location_costs
ON animals.location = location_costs.location;//

错误:“SET”处或附近的语法错误 SET animals.location_cost = location_costs.costs

我附上一张图片,这里给出了表格和列的想法:

Tables View

我无法破译错误,如果有人可以帮助我处理此代码,我将不胜感激。

谢谢。

【问题讨论】:

  • update animals 不是 update anmials.* - 但是 Postgres 您不应该在 FROM 子句中重复目标表以及您执行此操作的方式,它会创建 animals 表与自身的交叉连接,因为目标表和 FROM 子句中的表之间没有“连接条件”。
  • 我最初使用更新动物-这给了我错误:表名“动物”指定了不止一次(重复别名)。你是对的重复表创建错误,我该如何解决那?感谢您的回复。
  • 动物表中是否有引用location_cost表的位置列的外键?动物表的主键是什么?
  • location_cost 表只有 2 列:位置和成本。动物表有以下列:animalid、size、color、birthdate、weight、location、location_cost(这个需要更新)

标签: sql postgresql join sql-update


【解决方案1】:

如果您只想更新animals 中与location 匹配的location_costs 中的行,请使用以下语法:

UPDATE animals
SET location_cost = location_costs.costs
FROM location_costs
WHERE location_costs.location = animals.location;

如果要更新animals 的所有行(即使location_costs 中没有匹配location 的行也会更新为null),那么使用相关子查询:

UPDATE animals
SET location_cost = (
  SELECT location_costs.costs 
  FROM location_costs 
  WHERE location_costs.location = animals.location
);

【讨论】:

  • 您推荐的第一个代码有效!动物表下的位置值在位置成本下具有匹配的位置值,因此它没有返回任何空值。非常感谢您的帮助!
【解决方案2】:

如果 animalid 是具有唯一值的列,请尝试使用别名,如下所示:

Update animals
Set location_cost = location_costs.costs
From animals As a Left Join location_costs On (a.location = location_costs.location)
Where animals.animalid = a.animalid;

【讨论】:

  • 出现以下错误:UndefinedColumn) 关系“animals”的列“animals”不存在,尽管 animalid 具有唯一值。
  • @ramsha chowdhrey 我已删除“设置”部分中 location_cost 列的表前缀。试试修改后的版本。
  • 感谢您的帮助。 forpas 共享的代码也是一个很好的解决方案。
  • @ramsha chowdhrey 不客气。请勾选最合适的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-21
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
相关资源
最近更新 更多