[英]PostgreSQL update a table from another one joined as many to many
我有三個表: user
、 image
和user_images_image
(因為前兩個與 ManyToMany 相關)。 我想將user
表的profile_pic
設置為從image
表中獲取的name
屬性的值。
我知道如何為這樣的事情構建一個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;
在 PostgreSQL 中,我不能像在 MySQL 中那樣連接兩個表。
我該如何編寫這樣的查詢?
在 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 = ?
如果沒有丟失圖像,則替代方法是相關子查詢:
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.