简体   繁体   English

Postgresql 将列从一个表更新到另一个表

[英]Postgresql update column from one table to another

How do i update inventory_id in TABLE2 from TABLE1 inventory_id?如何从 TABLE1 inventory_id 更新 TABLE2 中的 inventory_id?

So far I've tried到目前为止我已经尝试过

UPDATE TABLE2
SET 
inventory_id=t1.inventory_id
FROM TABLE2 t2
INNER JOIN
TABLE1 t1
ON t1.test_id = t2.test_id
WHERE t1.test_id = t2.test_id;

But this sets all the value of inventory_id in TABLE2 as 1 instead of my expected result.但这将 TABLE2 中 inventory_id 的所有值设置为 1 而不是我的预期结果。

TABLE1
inventory_id     test_id
1                         26
2                         56
3                         12
4                         67
TABLE2
test_id       inventory_id
12
26
56
67

Such that it becomes like this?就这样变成了这样?

TABLE2
test_id       inventory_id
12              3
26              1
56              2
67              4

The documentation on UPDATE states: UPDATE上的文档指出:

 UPDATE [ ONLY ] table_name [ * ] [ [ AS ] alias ]... [ FROM from_item [, ...] ]

(...) (...)

from_item

A table expression allowing columns from other tables to appear in the WHERE condition and update expressions.允许其他表中的列出现在WHERE条件和更新表达式中的表表达式。 This uses the same syntax as the FROM clause of a SELECT statement;这使用与SELECT语句的FROM子句相同的语法; for example, an alias for the table name can be specified.例如,可以指定表名的别名。 Do not repeat the target table as a from_item unless you intend a self-join (in which case it must appear with an alias in the from_item ).不要将目标表作为from_item重复,除非您打算进行自连接(在这种情况下,它必须在from_item中以别名出现)。

(emphasis: me) (重点:我)

So following that you want:所以按照你想要的:

UPDATE table2 t2
       SET inventory_id = t1.inventory_id
       FROM table1 t1
            WHERE t1.test_id = t2.test_id;

db<>fiddle db<>小提琴

You pretty much had it but seem to got confused by the syntax you may have seen for other DBMS and mixed them.您几乎拥有它,但似乎对您可能在其他 DBMS 中看到的语法感到困惑,并将它们混合在一起。

Normally the PostgreSQL UPDATE JOIN syntax should give:通常 PostgreSQL UPDATE JOIN 语法应该给出:

UPDATE TABLE2 t2
SET 
t2.inventory_id=t1.inventory_id
FROM TABLE1 t1
WHERE t1.test_id = t2.test_id;

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

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