简体   繁体   English

PostgreSQL 从另一个表更新一个表,连接成多对多

[英]PostgreSQL update a table from another one joined as many to many

I have three tables: user , image and user_images_image (cos the first two related as ManyToMany).我有三个表: userimageuser_images_image (因为前两个与 ManyToMany 相关)。 I would like to set the profile_pic of the user table to the value of the name property taken from the image table.我想将user表的profile_pic设置为从image表中获取的name属性的值。

I know how to build a SELECT query for something like this but it's not very helpful... I would write something like this:我知道如何为这样的事情构建一个SELECT查询,但这不是很有帮助......我会写这样的东西:

SELECT "user".id, image.name FROM "user"
LEFT JOIN user_images_image uii ON "user".id = uii."userId"
LEFT JOIN image ON uii."imageId" = image."id"
WHERE "user".id = 2;

In PostgreSQL I can't just join two tables the way I would in MySQL.在 PostgreSQL 中,我不能像在 MySQL 中那样连接两个表。

How do I write such a query?我该如何编写这样的查询?

In Postgres, you would use the update/join syntax as follows:在 Postgres 中,您将使用如下更新/连接语法:

update "user" u
set profile_pic = i.name
from user_images_image uii
inner join image i on uii."imageId" = i."id"
where uii."userId" = u.id and u.id = ? and i.id = ?

If there are no missing images, then an alternative is a correlated subquery:如果没有丢失图像,则替代方法是相关子查询:

update "user" u
set profile_pic = (
    select i.name
    from user_images_image uii
    inner join image i on uii."imageId" = i."id"
    where uii."userId" = u.id and i.id = ?
) 
where u.id = ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM