我需要在某些PostgreSQL数据库表的其他列上更新条件值conditionnaly .我设法在R中编写一个SQL语句并dbExecute从DBI包中执行它.
library(dplyr)
library(DBI)
# Establish connection with database
con <- dbConnect(RPostgreSQL::PostgreSQL(), dbname = "myDb",
host="localhost", port= 5432, user="me",password = myPwd)
# Write SQL update statement
request <- paste("UPDATE table_to_update",
"SET var_to_change = 'new value' ",
"WHERE filter_var = 'filter' ")
# Back-end execution
con %>% dbExecute(request)
Run Code Online (Sandbox Code Playgroud)
是否可以仅使用dplyr语法执行此操作?出于好奇,我试过了
con %>% tbl("table_to_update") %>%
mutate(var_to_change = if (filter_var == 'filter') 'new value' else var_to_change)
Run Code Online (Sandbox Code Playgroud)
它在R中工作但显然在db中没有任何作用,因为它使用了一个select语句.copy_to只允许append和overwite选项,所以我看不到如何使用它,除非删除然后附加过滤后的观察...