r - 尝试在 R-ERROR : operator does not exist: character varying = integer 中使用 PostgreSQL 进行查询

标签 r postgresql

我正在使用 PostgreSQL 包通过 R 查询数据库。我想从数据表 cond 中提取所有列,其中列 id 是观察 ID 键,向量 of_interest 是我希望获得其信息的观察 ID 的子集。 R 中的 of_interest 向量看起来像这样:

of_interest <- c(1:5)

我写了一个查询然后像这样执行它:

query = paste('SELECT *
              FROM cond 
              WHERE id IN (',paste(of_interest,collapse=','),')')

COND = as.data.table(db.query(query, con=fia.con))

然后我收到以下错误:

Error in postgresqlExecStatement(conn, statement, ...) : 
  RS-DBI driver: (could not Retrieve the result : ERROR:  operator does not exist: character varying = integer
LINE 4:               WHERE id IN ( 1,2,3,4,5 )
                               ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

知道这里可能出了什么问题吗?过去,我可以通过将查询结构化为基于 ID 轻松查询:

SELECT *
FROM cond
WHERE id IN (1,2,3,4,5)

这是 sessionInfo() 的结果

R version 3.1.2 (2014-10-31)
Platform: x86_64-redhat-linux-gnu (64-bit)

locale:
[1] C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] rgdal_0.8-16     raster_2.2-31    sp_1.0-15        car_2.0-19       bit64_0.9-5      bit_1.1-12       RPostgreSQL_0.4  DBI_0.3.1        data.table_1.9.6

loaded via a namespace (and not attached):
[1] MASS_7.3-35     chron_2.3-45    grid_3.1.2      lattice_0.20-29 nnet_7.3-8      tools_3.1.2    

最佳答案

这是我的例子:

library(RPostgreSQL)

Configuration.db.host.local <- "localhost"
Configuration.db.user.local <- "postgres"
Configuration.db.password.local <- "your password"
Configuration.db.dbname.local <- "your dbname"

local_con <- dbConnect(PostgreSQL(), host=Configuration.db.host.local, user= Configuration.db.user.local,password=Configuration.db.password.local, dbname=Configuration.db.dbname.local)

of_interest <- c(1:5)
query = paste('SELECT *
              FROM cond 
              WHERE id IN (',paste(of_interest,collapse=','),')')

data <- dbGetQuery(local_con, query)

更新:

看来你提交的是字符串。在这种情况下尝试使用这段代码:

expr = paste0("('",paste(of_interest, collapse="','"),"')")
query = paste("SELECT *
              FROM cond 
              WHERE id IN ", expr)

关于r - 尝试在 R-ERROR : operator does not exist: character varying = integer 中使用 PostgreSQL 进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34206102/

相关文章:

sql - 我们如何向结果集中添加一列以显示 PostgreSQL 中的计数?

r - 如何在具有范围的 data.frame 中生成随机数

r - 在 testthat 中抛出警告而不是错误

postgresql - 如何在 psql 中获取多个函数?

sql - 添加约束以确保两个外键的公共(public)父级

postgresql - 在 phpPgadmin 中创建程序

r - 在 NA 上传播值

r - 插入符号中的 closeZeroVar 函数

r - 使用 R 制作 gif 动画

database - 在 Kubernetes 中运行数据库是一种反模式吗?