RPostgreSQL-基于主键的向量查询表的主键

时间:2018-08-03 13:57:34

标签: r join primary-key rpostgresql

问题:如何使用RPostgreSQL基于包含主键向量的变量来查询数据库表?

示例:在此示例中,我有以下代码可用于一个实例,但在尝试对其进行矢量化处理时不起作用。

library(RPostgreSQL)

Pkey <- 100231

connect <- dbConnect(PostgreSQL(), 
           dbname="test",
           host="localhost",
           port=5432,
           user="user", 
           password="...")

query <- paste0("SELECT * FROM sales_tbl WHERE id='", Pkey, "'")
result <- dbGetQuery(connect, query)

矢量化Pkey示例(无效)

library(RPostgreSQL)

Pkey <- list$Pkey # This is the change.

connect <- dbConnect(PostgreSQL(), 
           dbname="test",
           host="localhost",
           port=5432,
           user="user", 
           password="...")

query <- paste0("SELECT * FROM sales_tbl WHERE id='", Pkey, "'")
result <- dbGetQuery(connect, query)

1 个答案:

答案 0 :(得分:0)

使用glue软件包:

query <- glue::glue_sql("SELECT * FROM sales_tbl WHERE id IN ({Pkey*})",
                        .con = connect)

来源和建议阅读:http://db.rstudio.com/best-practices/run-queries-safely/