【问题标题】:RSQLite insert ignore to skip duplicatesRSQLite 插入忽略以跳过重复项
【发布时间】:2023-03-13 11:20:01
【问题描述】:

我有一个包含 x、y 和 z 列的 sqlite 表。 x 和 y 是唯一键,z 是值。

我想用 R 向这个表中插入数据。如果正在插入基于 x 和 y 字段的重复记录,我希望 sqlite 拒绝该记录并继续。在sql中,这可以使用“插入或忽略”来完成,这可以使用R包RSQLite来完成吗?到目前为止,有一个选项 dbWriteTable 将 R 数据帧写入 sqlite 表,但似乎没有“插入或忽略”选项

【问题讨论】:

    标签: sql r sqlite


    【解决方案1】:

    我找到了 dbWriteTable 构造 sql 字符串并将其发送到 sqlite 的源。您可以使用此修改后的源来允许“插入或忽略”语法

    https://gist.github.com/jeffwong/5925000

    【讨论】:

      【解决方案2】:

      对@Karsten W 的回答进行返工,以使用相同的流程加载所有数据:

      library(RSQLite)
      
      # create table
      con <- dbConnect(drv=RSQLite::SQLite(), ":memory:")
      dbExecute(con, "CREATE TABLE tab1 (a CHAR(6) NOT NULL, b CHAR(6) NOT NULL, PRIMARY KEY (a, b));")
      
      load_data <- function(x) {
          # load data
          # we want to add only the new combinations of a and b
          insertnew <- dbSendQuery(con, "INSERT OR IGNORE INTO tab1 VALUES (:a,:b)")
          dbBind(insertnew, params=x)  # execute
          dbClearResult(insertnew)     # release the prepared statement
      }
      
      
      # new data
      dat1 <- data.frame(a=letters[1:10], b=LETTERS[11:20], stringsAsFactors=FALSE)
      load_data(dat1)
      print(dbGetQuery(con, "SELECT COUNT(*) FROM tab1;"))
      
      # new data, partly redundant
      dat1 <- data.frame(a=letters[2:11], b=LETTERS[12:21], stringsAsFactors=FALSE)
      load_data(dat1)
      print(dbGetQuery(con, "SELECT COUNT(*) FROM tab1;"))
      

      【讨论】:

        【解决方案3】:
        results <- dbSendQuery(exampledb, "insert or ignore ...") 
        

        dbSendQuery 采用原始 SQL,根据 DBI spec。希望对您有所帮助...

        【讨论】:

          【解决方案4】:

          由于我有类似的问题,这里是一个一次性的解决方案:

          library(RSQLite)
          
          # create table
          con <- dbConnect(drv=RSQLite::SQLite(), ":memory:")
          dbExecute(con, "CREATE TABLE tab1 (a CHAR(6) NOT NULL, b CHAR(6) NOT NULL, PRIMARY KEY (a, b));")
          dat1 <- data.frame(a=letters[1:10], b=LETTERS[11:20], stringsAsFactors=FALSE)
          dbWriteTable(con, "tab1", dat1, append=TRUE)
          
          # new data, partly redundant
          dat2 <- data.frame(a=letters[2:11], b=LETTERS[12:21], stringsAsFactors=FALSE)
          
          # we want to add only the new combinations of a and b
          insertnew <- dbSendQuery(con, "INSERT OR IGNORE INTO tab1 VALUES (:a,:b)")
          dbBind(insertnew, params=dat2) # execute
          dbClearResult(insertnew)  # release the prepared statement
          
          # should be TRUE
          as.numeric(dbGetQuery(con, "SELECT COUNT(*) FROM tab1;"))==11
          

          【讨论】:

            猜你喜欢
            • 2012-08-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-10-22
            • 2020-01-03
            • 1970-01-01
            • 1970-01-01
            • 2023-03-06
            相关资源
            最近更新 更多