r在sql where语句中的列值

时间:2015-02-18 22:21:11

标签: sql r sqldf

我有一个数据集,我试图将特定列的内容传递给SQL where语句。

例如,假设虹膜是我的数据集

       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语句

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

需要帮助

2 个答案:

答案 0 :(得分:3)

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

vals = paste(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)"

答案 1 :(得分:1)

通过gsubfn package字符串中的fn$对任何函数调用进行前缀,在其参数上启用插值。有关详细信息,请参阅?fn。这通常与sqldf package中的sqldf一起使用,但可以与我们在此处显示的任何函数一起使用。特别是将$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")