【问题标题】:POSTGRES Update with left outer join is not working带有左外连接的 POSTGRES 更新不起作用
【发布时间】:2020-07-02 11:53:41
【问题描述】:

请建议,我做错了什么。

UPDATE uc 
SET uc.selected_value_id = cv.id, uc.fixed_value = NULL
FROM unit_characteristic uc
left JOIN characteristic_value cv ON uc.fixed_value like CONCAT(cv.value,'%')  
WHERE cv.characteristic_id = 6 
and uc.characteristic_id = 6
and uc.unit_id in (6313,6314)

遇到错误

SQL 错误 [42P01]:错误:关系“uc”不存在 职位:8 org.postgresql.util.PSQLException:错误:关系“uc”不存在 位置:8

虽然此选择工作正常

select count(uc.*)   
FROM unit_characteristic uc
left JOIN characteristic_value cv ON uc.fixed_value like CONCAT(cv.value,'%')  
WHERE cv.characteristic_id = 6 
and uc.characteristic_id = 6
and uc.unit_id in (6313,6314)

【问题讨论】:

  • UPDATE ... FROM LEFT JOIN 无论如何都没有意义。幸运的是,WHERE cv.characteristic_id = 6 将 LEFT 连接变成了普通的内部连接。
  • 如果我使用左连接或使用位置没有区别,两者的时间都得到相同的错误。
  • 注释是关于语义的,而不是关于语法的。
  • (关于 wildplasser 的 cmets,它与您的代码有关,但与您的错误消息无关:) LEFT JOIN ON 返回 INNER JOIN ON 行 UNION ALL 不匹配的左表行,由 NULL 扩展。作为 OUTER JOIN ON 的一部分,始终知道您想要什么 INNER JOIN ON。在 LEFT JOIN ON 之后,需要右 [sic] 表列不为 NULL 的 WHERE、INNER JOIN 或 HAVING 会删除任何引入了 NULL 的行,即只保留 INNER JOIN ON 行,即“将 OUTER JOIN 转换为 INNER JOIN” .你有那个。

标签: sql postgresql sql-update left-join


【解决方案1】:
  • 您不必在FROM 子句中重复target 表;它已经在范围表中
  • 目标表可以有别名
  • 但是,SET columnname = new_value不得使用此别名。它是隐式的(因为只有一个表引用要更新)

UPDATE unit_characteristic uc 
   SET selected_value_id = cv.id
     , fixed_value = NULL
FROM characteristic_value cv 
WHERE uc.fixed_value like cv.value || '%'
 AND cv.characteristic_id = 6
 AND uc.characteristic_id = 6
 AND uc.unit_id in (6313, 6314)
   ;

【讨论】:

  • 得到了解决方案。这是导致问题的列名的别名。
  • update public.unit_characteristic uc set selected_value_id = cv.id, fixed_value = NULL from public.characteristic_value cv where uc.fixed_value like cv.value || '%' 和 cv.characteristic_id = 6 和 uc.characteristic_id = 6
  • 这就是我写的。
【解决方案2】:

在 Postgres 中,update 中的引用不能引用 from 中的表。我怀疑你想要:

update unit_characteristic uc 
    set selected_value_id = cv.id,
        fixed_value = NULL
from characteristic_value cv 
where uc.fixed_value like cv.value || '%' and
      cv.characteristic_id = 6 and
      uc.characteristic_id = 6 and
      uc.unit_id in (6313, 6314);

请注意,您的查询版本使用left join。但是where 子句将其变成了内连接。

【讨论】:

  • 仍然收到错误 SQL 错误 [42703]:错误:关系“unit_characteristic”的列“uc”不存在位置:40 org.postgresql.util.PSQLException:错误:列“uc”的关系“unit_characteristic”不存在位置:40
  • @TanuGarg 。 . .所有比较和列引用都来自您的查询。您尚未指定表格或提供示例数据。因此,请修复条件,使其与您的数据相匹配。
  • 得到了解决方案。这是导致问题的列名的别名。更新 public.unit_characteristic uc set selected_value_id = cv.id, fixed_value = NULL from public.characteristic_value cv where uc.fixed_value like cv.value || '%' 和 cv.characteristic_id = 6 和 uc.characteristic_id = 6
  • @TanuGarg 。 . . set 的左侧不需要它们。
猜你喜欢
  • 2012-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-05
相关资源
最近更新 更多