【问题标题】:How to delete table based on timestamps in R Mysql DB?如何根据 R Mysql DB 中的时间戳删除表?
【发布时间】:2020-01-22 03:14:34
【问题描述】:

这是我的时间戳

q1<-Sys.time()-777000 
q1
#"2019-09-12 08:39:27 GMT"

这是我正在尝试做的,我得到一个错误

Sys.time()
dbSendQuery(conn,"delete from anomaly_hourly_temp  where report_time>q1")
Sys.time()
dbSendQuery(conn,"delete from anomaly_hourly_temp  where report_time>q1")

.local(conn, statement, ...) 中的错误: 无法运行语句:“where 子句”中的未知列“q1”

也试过这个,虽然它没有显示任何错误,但它不会根据时间戳删除任何行

Sys.time()
dbSendQuery(conn,"delete from anomaly_hourly_temp  where report_time>'q1'")
Sys.time()

如果我明确指定 timestamp(q1) ,它的工作原理如下

dbSendQuery(conn,"delete from anomaly_hourly_temp  where report_time>'2019-09-22 11:42:51'")

【问题讨论】:

  • q 中删除尾随GMT
  • 我从我的 q1 中删除了 GMT,如下所示 q1

标签: mysql r dplyr rmysql


【解决方案1】:

现在您尝试将 R 变量插入到 SQL 语句中,但 SQL 读取的是文字 q1 而不是它的基础值。虽然将 R 变量连接到 SQL 字符串是一种解决方案,但在后续步骤中使用带有参数绑定的准备好的语句运行参数化更安全、更高效、避免引号和行业最佳实践:

# PREPARED STATEMENT
sql <- "delete from anomaly_hourly_temp  where report_time > ?")

# BIND PARAM AND EXECUTE ACTION
dbSendQuery(conn, sql, list(q))

【讨论】:

    【解决方案2】:

    使用paste0 将查询粘贴在一起。

    DBI::dbSendQuery(conn, 
         paste0("delete from anomaly_hourly_temp where report_time > '", q1, "'"))
    

    类似于paste0,我们也可以使用paste/str_c/glue/sprintf或其他有助于将查询粘贴在一起的功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 2020-11-03
      相关资源
      最近更新 更多