sql where 语句中的 r 列值

r column values in sql where statement

我有一个数据集,我正在尝试将特定列的内容传递到 SQL where 语句中。

例如,假设 iris 是我的数据集

       data(iris)
       head(iris)

       Sepal.Length Sepal.Width Petal.Length Petal.Width Species
       5.1         3.5          1.4         0.2  setosa
       4.9         3.0          1.4         0.2  setosa
       4.7         3.2          1.3         0.2  setosa
       4.6         3.1          1.5         0.2  setosa
       5.0         3.6          1.4         0.2  setosa
       5.4         3.9          1.7         0.4  setosa

我想将列 Species { setosa, setosa, setosa.....setosa} 的内容传递给我的 sql 查询 where statement

sqlQuery(abcd, paste("Select * from TestTableName1 
                       where WHERE DESCRIPTION 
                          IN (values of Species column from r dataframe)");

这里需要帮助

你的问题实际上是关于字符串操作(你的字符串最终会被传递给sqldf是偶然的),答案是你把它粘贴在一起,或者如果你使用sprintf感觉很不错:

vals = paste(paste0('"', levels(iris$Species), '"'), collapse = ", ")
vals
## [1] "\"setosa\", \"versicolor\", \"virginica\""

vals.paren = paste0("(", vals, ")")

qry = paste("select * from table where description in ", vals.paren)
qry
## [1] "select * from table where description in  (setosa, versicolor, virginica)"

# sprintf makes the bounding parentheses cleaner

qry = sprintf("select * from table where description in (%s)", vals)
qry
## [1] "select * from table where description in (setosa, versicolor, virginica)"

通过使用 gsubfn package string interpolation is enabled on its arguments. See ?fn for more info. This is often used with sqldf in the sqldf package 中的 fn$ 作为任何函数调用的前缀,但可以与我们在此处展示的任何函数一起使用。特别是将 $variable 插入到函数调用的字符串参数中,将该变量的值替换为该字符串:

library(gsubfn)
lvls <- toString(shQuote(levels(iris$Species)))

fn$sqlQuery(abcd,  "select * from TestTableName1 where DESCRIPTION in ($lvls)")

或者如果我们想先检查字符串:

sql <- fn$identity("select * from TestTableName1 where DESCRIPTION in ($lvls)")
cat(sql, "\n") # look at sql string

sqlQuery(abcd, sql)

cat 语句的输出是:

select * from TestTableName1 where DESCRIPTION in ("setosa", "versicolor", "virginica")