简体   繁体   English

PostgreSQL 更新 + 加入一个额外的 WHERE 子句

[英]PostgreSQL update + join with an additional WHERE clause

I need to use JOIN in my UPDATE so that I would only fill the value of the column where the condition applies.我需要在我的 UPDATE 中使用 JOIN 以便我只填充条件适用的列的值。

I was trying to do this, but I receive an error saying "syntax error at or near 'LEFT'":我试图这样做,但我收到一条错误消息,提示“'LEFT'处或附近的语法错误”:

UPDATE products_mpn SET scrap = 5
LEFT JOIN products ON products.id = products_mpn.product
WHERE products.category_id = 101 OR products.category_id = 104

I have found that I could join the tables this way:我发现我可以通过这种方式加入表格:

UPDATE t1
SET t1.c1 = new_value
FROM t2
WHERE t1.c2 = t2.c2;

But the issue is that I can not use my specific WHERE clause then.但问题是我不能使用我的特定 WHERE 子句。 Any ideas on how to achieve this?关于如何实现这一目标的任何想法?

Try this:试试这个:

UPDATE products_mpn SET scrap = 5 WHERE product = ( SELECT product FROM products_mpn
LEFT JOIN products ON products.id = products_mpn.product
WHERE products.category_id = 101 OR products.category_id = 104)
UPDATE products_mpn SET scrap = 5 WHERE product IN ( SELECT id FROM products WHERE category_id IN (101,104))

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

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