Postgres update with an inner join across 2 tables?

江枫思渺然 提交于 2019-12-05 19:02:44

问题


I have 3 tables in my local Postgres database:

[myschema].[animals]
--------------------
animal_id
animal_attrib_type_id (foreign key to [myschema].[animal_attrib_types])
animal_attrib_value_id (foreign key to [myschema].[animal_attrib_values])

[myschema].[animal_attrib_types]
--------------------------------
animal_attrib_type_id
animal_attrib_type_name

[myschema].[animal_attrib_values]
--------------------------------
animal_attrib_value_id
animal_attrib_value_name

At runtime I will know the animal_id. I need to run SQL to update the animal_attribute_value_name associated with this item, so something like:

UPDATE
    animal_attribute_values aav
SET
    aav.animal_attribute_value_name = 'Some new value'
WHERE
    # Somehow join from the provided animal_id???

I may have to do some kind of nested SELECT or INNER JOIN inside the WHERE clause, but not sure how to do this. Thanks in advance!

Edit:

Let's say I have an animal record with the following values:

[myschema].[animals]
--------------------
animal_id = 458
animal_attrib_type_id = 38
animal_attrib_value_id = 23

And the corresponding animal_attrib_value (with id = 23) has the following values:

[myschema].[animal_attrib_values]
--------------------------------
animal_attrib_value_id = 23
animal_attrib_value_name = 'I am some value that needs to be changed.'

At runtime, I only have the animal_id (458). I need to look up the corresponding animal_attrib_value (23) and change its animal_attrib_value_name to 'Some new value', all inside of a single UPDATE statement.


回答1:


UPDATE
    animal_attribute_values aav
SET
    animal_attribute_value_name = 'Some new value'
FROM animals aa
WHERE aa.animal_id = 458
AND aa.animal_attrib_value_id = aav.animal_attrib_value_id
  ;



回答2:


are you asking something like this right..?

update  animal_attribute_values aav
set  aav.animal_attribute_value_name = 'Some new value'
where aav.animal_attrib_value_id in (
select a.animal_attrib_value_id where a.animal_id=458)

try this..



来源:https://stackoverflow.com/questions/12600608/postgres-update-with-an-inner-join-across-2-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!