sql - 将一个表中的值赋给另一个表

标签 sql postgresql sql-update dml

有两个表 Table A 和 Table B。它们包含相同的列 cost 和 item。表 B 包含项目列表及其相应的成本,而表 A 仅包含项目列表。

现在我们需要检查表A中的项目,如果它们存在于表B中,那么相应的项目成本应该分配给表A中的项目成本。

有人可以为此写一个查询来帮助我吗。

考虑如图所示的表格:

表A:

item    cost
------------- 
pen     null
book    null
watch   null

表 B:

item     cost
------------- 
watch    1000
book     50

预期输出

Table A:

item    cost
pen       0
book     50
watch   1000

最佳答案

只需在表 B 中添加一个外键(表 A 的主键),就像表 A ID 然后在查询中添加一个连接(可能是右连接)以获取或分配各个项目的价格。

加入就像

SELECT item, cost
    FROM tablename a
    RIGHT JOIN tablename b ON a.item= b.item;

编辑:

只需编辑此表名,即可运行。

关于sql - 将一个表中的值赋给另一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54570606/

相关文章:

mysql - mySQL 中每个子查询的最大值

java - 使用 hibernate select 获取时间戳字段的错误时间

mysql - 如何在 MySQL 的 SET 子句中使用 SELECT 子句?

sql - 如何更正 ‘One to Many table’ 在 PL/pgSQL 中缺少引用?

Android SQLite : How to update one column of all records with different values

sql - Ruby on Rails : Finding the sum of a column in a returned search query

mysql - 使用 JOIN 而不是 WHERE OR... IN 子查询

sql - 如何快速批量更新postgres中的序列号

java - 第二次访问时为空数据

sql - 如何向 epgsql sql where in 子句提供列表 (Erlang)