R sqlite: update with two tables gives syntax erro

2019-08-01 17:52发布

问题:

I would like to do a UPDATE with two tables on sqlite.

x1 <- data.frame(id = rep(1,3),
                  t = as.Date(c("2000-01-01","2000-01-15","2000-01-31"))
)
x1.h <- 0
x2 <- data.frame(id = 1, start = as.Date("2000-01-14"))

The UPDATE is:

sqldf(paste("UPDATE x1"
        ," SET x1.h = 1"
        ," WHERE EXISTS (SELECT *"
        ,"               FROM x2"
        ,"               WHERE x1.id = x2.id"
        ,"                     AND x1.t < x2.start"
        ,"               )"
        )
  )

I get the following error:

Error in sqliteExecStatement(con, statement, bind.data) : 
   RS-DBI driver: (error in statement: near ".": syntax error)

Has someone an idea what goes wrong? Thanks for helps.

回答1:

Why are u using sqldf to update? I think sqldf is ony for select statement.

I would use RSQLite to this.

First I correct your sql statetemnt. I prefer use sep '\n' , to get pretty request with cat

str.update <- paste(" UPDATE x1"
            ," SET h = 1 "              ## here the error
            ," WHERE EXISTS (SELECT * "
             ,"              FROM x2 "             ## here second error 
             ,"              WHERE x1.id = x2.id "
            ,"               AND x1.t < x2.start "
            ,"       )"
      ,sep ='\n'
)


cat(str.update)
 UPDATE x1
 SET h = 1 
 WHERE EXISTS (SELECT * 
              FROM x1,x2    ##
              WHERE x1.id = x2.id 
               AND x1.t < x2.start 
       )

Then you can do this :

library(RSQLite)
con <- dbConnect(SQLite(), ":memory:")
dbWriteTable(con, "x1", x1)            # I create my table x1
dbWriteTable(con, "x2", x2)            # I create my table x2
res <- dbSendQuery(con, str.update)   
dbReadTable(con,name='x1')            ## to see the result

Edit

I edit my answer after Op clarifications (FROM x1,x2 becomes FROM x2)



回答2:

I found this solution:

x1$h <- 0
x1 <- sqldf(c("UPDATE x1
        SET h = 1
        WHERE EXISTS (SELECT x1.id
                        FROM x2
                        WHERE x1.id = x2.id
                          AND x1.t < x2.start
                     )",
        "SELECT * FROM main.x1"))

Giving:

> x1

  id          t h
1  1 2000-01-01 1
2  1 2000-01-15 0
3  1 2000-01-31 0

Source: https://code.google.com/p/sqldf/#8._Why_am_I_having_problems_with_update? Other things to remind: obviously alias do not work, for example UPDATE x1 a ... Thanks for help.



回答3:

I think your inner SELECT doesn't say where its selecting from. Try it separately. I thought it should look more like:

SELECT * FROM x1,x2 WHERE x1.id = x2.id AND x1.t < x2.start