简体   繁体   English

SQL更新“目标”表以使用“源”表实现“结果”表

[英]SQL update 'target' table to achieve 'result' table using 'source' table

There is a table 'target' that looks like this: 有一个表“目标”如下所示:

id val
1 A 1个
2 A 2个
3 3

5 A 5安
8 A 8个
9 9

There is also a 'source' table that looks like this 还有一个“源”表看起来像这样
id val
1 1
2 B 2个

4 B 4个

8 B 8层
9 B 9号

The directioins ask to use the 'source' table to transform the 'target' table into the 'result' table, which looks like this: 指令要求使用“源”表将“目标”表转换为“结果”表,如下所示:

result 结果
id val
1 1
2 B 2个
3 3

5 A 5安
8 B 8层
9 B 9号

I understand the logic of what the question is asking, as I believe what I need to do is basically say 我了解问题的逻辑,因为我认为我基本上要做的是说

IF target.id = source.id  
SET target.val = source.val  
ELSE target.val = target.val  

However, I am not completely sure how to accomplish this kind of update in SQL based on conditions w/ multiple tables using postgresql. 但是,我不确定如何使用postgresql根据带有多个表的条件在SQL中完成这种更新。

This looks like homework so I won't give a complete answer. 这看起来像是作业,所以我不会给出完整的答案。

First step is to turn these into tables you can actually use. 第一步是将它们变成您可以实际使用的表。 A handy tool for this is provided by http://sqlfiddle.com , with its "text to table" feature. http://sqlfiddle.com提供了一个方便的工具,它具有“文本到表格”功能。 Because of the dodgy formatting of the input we've got to make some fixups before it'll work (assuming empty cols are null, not empty string; fixing whitespace errors) but then we get: 由于输入内容的格式很笨拙,因此我们必须先进行一些修正(在使用之前,先进行一些修正)(假设空cols为null,而不是空字符串;修正空白错误),然后我们得到:

http://sqlfiddle.com/#!15/4a046 http://sqlfiddle.com/#!15/4a046

(SQLfiddle is far from a model of how you should write DDL - it's a useful debugging tool, that's all). (SQLfiddle远不是应该如何编写DDL的模型-仅此而已,它是一个有用的调试工具)。

So now you have something to play with. 因此,现在您可以玩一些东西了。

At this point, I suggest looking into the UPDATE ... FROM statement , which lets you update a join. 在这一点上,我建议研究UPDATE ... FROM语句 ,该语句可让您更新UPDATE ... FROM Or you can use a subquery in UPDATE to perform the required logic. 或者,您可以在UPDATE使用子查询来执行所需的逻辑。

UPDATE target
SET val = source.val
FROM /* you get to fill this in */
WHERE /* you get to fill this in */

Merging data 合并资料

Luckily, the result table they've given you is the result of a simple join-update. 幸运的是,他们给您的结果表是一个简单的join-update的结果。 Note that rows present in "source" but not "target" haven't been added to "result" 请注意,“源”中存在的行而不是“目标”中存在的行尚未添加到“结果”中

If you were instead supposed to merge the two, so that entries in source that do not exist in target at all get added to target , this becomes what's called an upsert. 如果您应该合并两者,那么source中根本不存在于target中的条目将被添加到target ,这就是所谓的upsert。 This has been written about extensively; 这已经被广泛地写过了。 see links included in this post . 请参阅这篇文章中包含的链接 Be glad you don't have to deal with that. 很高兴您不必处理这些。

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

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