基本上,我想这样做:
update vehicles_vehicle v
join shipments_shipment s on v.shipment_id=s.id
set v.price=s.price_per_vehicle;
我很确定这在MySQL(我的背景)中可以工作,但在postgres中似乎不起作用。我得到的错误是:
ERROR: syntax error at or near "join"
LINE 1: update vehicles_vehicle v join shipments_shipment s on v.shi...
^
当然有一个简单的方法来做到这一点,但我找不到合适的语法。那么,我该如何在PostgreSQL中写这个呢?
UPDATE语法为:
[ WITH [ RECURSIVE ] with_query [, ...] ]
UPDATE [ ONLY ] table [ [ AS ] alias ]
SET { column = { expression | DEFAULT } |
( column [, ...] ) = ( { expression | DEFAULT } [, ...] ) } [, ...]
[ FROM from_list ]
[ WHERE condition | WHERE CURRENT OF cursor_name ]
[ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]
在你的情况下,我认为你想要的是:
UPDATE vehicles_vehicle AS v
SET price = s.price_per_vehicle
FROM shipments_shipment AS s
WHERE v.shipment_id = s.id
或者如果你需要连接两个或多个表:
UPDATE table_1 t1
SET foo = 'new_value'
FROM table_2 t2
JOIN table_3 t3 ON t3.id = t2.t3_id
WHERE
t2.id = t1.t2_id
AND t3.bar = True;
在PostGRE SQL / AWS (SQL工作台)中使用另一个表更新一个表。
在PostGRE SQL中,你需要在UPDATE Query中使用join:
UPDATE TABLEA set COLUMN_FROM_TABLEA = COLUMN_FROM_TABLEB FROM TABLEA,TABLEB WHERE FILTER_FROM_TABLEA = FILTER_FROM_TABLEB;
Example:
Update Employees Set Date_Of_Exit = Exit_Date_Recorded , Exit_Flg = 1 From Employees, Employee_Exit_Clearance Where Emp_ID = Exit_Emp_ID
表A - Employees列表A - Date_Of_Exit,Emp_ID,Exit_Flg表B是- Employee_Exit_Clearance列表B - Exit_Date_Recorded,Exit_Emp_ID
1760行受影响
执行时间:29.18秒
在上面所有的答案中添加一些非常重要的东西,当你想要更新连接表时,你可能会遇到两个问题:
您不能使用您想要更新的表来JOIN另一个表
Postgres希望在JOIN之后有一个ON子句,因此不能只使用where子句。
这意味着基本上,以下查询是无效的:
UPDATE join_a_b
SET count = 10
FROM a
JOIN b on b.id = join_a_b.b_id -- Not valid since join_a_b is used here
WHERE a.id = join_a_b.a_id
AND a.name = 'A'
AND b.name = 'B'
UPDATE join_a_b
SET count = 10
FROM a
JOIN b -- Not valid since there is no ON clause
WHERE a.id = join_a_b.a_id
AND b.id = join_a_b.b_id
a.name = 'A'
AND b.name = 'B'
相反,你必须像这样使用FROM子句中的所有表:
UPDATE join_a_b
SET count = 10
FROM a, b
WHERE a.id = join_a_b.a_id
AND b.id = join_a_b.b_id
AND a.name = 'A'
AND b.name = 'B'
这对一些人来说可能很简单,但我被这个问题困住了,想知道发生了什么,所以希望它能帮助到其他人。