R:存在UNIQUE INDEX时,使用DBI或SQL替换RSQLite中的行

时间:2018-10-11 17:44:40

标签: r dbi rsqlite dbplyr

我有一个数据库,该数据库的列应该是唯一的(客户ID)以及相关的数据列(地址)。客户地址更改时,是否可以更新行?我宁愿使用dbplyr或DBI来执行此操作,就像使用SQL一样,我必须遍历行,否则我必须将所有数据加载到内存中,进行替换,然后重写表,即...不雅吗?

一个玩具示例:

library(dbplyr)
library(DBI)

# create toy dataset
df1 <- data.frame(a = c(1,2,3,4), b=c("a","b","c","d"), stringsAsFactors = F)
df2 <- data.frame(a = c(3,4), b=c("e","f"), stringsAsFactors = F)

df3 <- df1
df3[match(df2$a, df3$a), ] <- df2 # this is the desired result

# create toy RSQLite db
toy_db <- dbConnect(RSQLite::SQLite(),path=":memory:")
dbExecute(toy_db,"CREATE TABLE toy (a INTEGER, b TEXT)")
dbExecute(toy_db,"CREATE UNIQUE INDEX idx ON toy(a)")
copy_to(toy_db,df1,name="test_data")
toy_df <- tbl(toy_db,"test_data")
toy_df[match(df2$a,toy_df$a), ] <- df2 # doesn't work


dbDisconnect(toy_db)

0 个答案:

没有答案