根据行 ID 将值从 R 写入 PostgreSQL table

Write values from R to a PostgreSQL table based on Row IDs

我在本地服务器上有一个 PostgreSQL table Scores,如下所示:

ID   Score_X   Score_Y
1       NA        NA
2       NA        NA
3       NA        NA
4       NA        NA

我在 R 中进行了一系列计算,生成的数据帧 Calc_Scores 如下所示:

ID   Score_X   Score_Y
1      0.53      0.81
4      0.75      0.95

我想将与每个 ID 对应的分数从 R 写入 PostgreSQL table,这样最终的 PostgreSQL table 应该如下所示:

ID   Score_X   Score_Y
1      0.53      0.81
2       NA        NA
3       NA        NA
4      0.75      0.95

我有一个名为 connection 的 PostgreSQL table 连接,我使用函数 dbConnect() 设置了它。实际的 table 相当大。我可以使用 R 中的什么 line/code 将这些分数写入 PostgreSQL table?我一直在寻找类似的问题,但找不到任何东西。我试过了

dbWriteTable(connection, "Scores", value = Calc_Scores, overwrite=T, append = F, row.names = F)

但是,整个 table 都会被覆盖。我只想更新分数。

谢谢。

这样做的一种方法依赖于 SQL 'update' 并且本质上你做

- open a connection to your database
- loop over your changeset and for each row
    - form the update statement, i.e. for example via
      cmd <- paste('update table set x=', Score_x, ', y=', 
                   Score_y, ' where id=', id)
    - submit the cmd via eg `dbSendQuery`
- close the connection

RPostgreSQL.

中有例子

创建临时 table 可能是一种选择:

# Create temporary table
dbWriteTable(connection, "ScoresTmp", value = Calc_Scores, overwrite=T, append = F, row.names = F)

# Update main table
dbExecute(connection,"
UPDATE Scores
SET Score_X = ScoresTmp.Score_X,
    Score_Y = ScoresTmp.Score_Y
FROM ScoresTmp 
WHERE Scores.ID = ScoresTmp.ID
")

# Clean up
dbExecute(connection,"DROP TABLE ScoresTmp")

请注意,您应该能够使用 temporary=TRUE 选项创建一个真正的临时 table :根据下面的@Sirius 评论,它应该在 PostGreSQL 数据库上工作。
对于 SQLServer 数据库的用户,此选项不起作用,但他们可以使用 # 前缀创建临时 table.
在上面的示例中,这将是:

 dbWriteTable(connection, "#ScoresTmp", value = Calc_Scores, overwrite=T, append = F, row.names = F)