简体   繁体   English

在R语句中使用R子句的where子句在SQL语句中使用它

[英]Using where clause for R Variable in R script to use it in SQL statement

I have two tables; 我有两张桌子; viz table1 = PID (primary key) + 20 other columns & 200 records from database1 AND table2 = [Serial no] (primary key) + 10 other columns & 300 records from database2. viz table1 = PID(主键)+ 20个其他列&200个记录来自database1 AND table2 = [Serial no](主键)+10个其他列&300个记录来自database2。

I am trying to extract values from table2 where PID = [Serial no]. 我试图从table2中提取值,其中PID = [Serial no]。

Note: PID = [SCK34ICV7, NSCK876DL, ......]. 注意:PID = [SCK34ICV7,NSCK876DL,......]。

I refered "Pass string Variable in R script to use it in SQL statement" 我提到“在R脚本中传递字符串变量以在SQL语句中使用它”

t1 <- sqlquery(db1, "select * from table1")
r1 <- t1$PID
class(r1) = 'factor'
t2 <- sqlquery(db2, "select * from table2 where [Serial no] = '(",r1,")' ",sep ="")

I also tried other functions viz paste0(), fn$ from gsubfn and sprintf() and getting error like - 'c is not a recognized built in function name' ; 我还尝试了其他函数viz paste0(),fn $来自gsubfn和sprintf()并得到错误 - 'c不是公认的内置函数名'; 'Incorrect syntax'. '语法不正确'。

Please suggest the best way to do it. 请建议最好的方法。

Reg, 注册,

Mrutyunjaya Mrutyunjaya

Your query is off. 您的查询已关闭。 See here for what the proper format should be. 请参阅此处了解适当的格式。

r1 <- c("PID1","PID2","PID3")

wrong 错误

paste("select * from table2 where [Serial no] = '(",r1,")' ",sep ="")

output: 输出:

[1] "select * from table2 where [Serial no] = '(PID1)' " "select * from table2 where [Serial no] = '(PID2)' " "select * from table2 where [Serial no] = '(PID3)' "

correct 正确

paste("select * from table2 where [Serial no] IN (",paste(r1,collapse=", "),") ",sep ="")

Output: 输出:

[1] "select * from table2 where [Serial no] IN (PID1, PID2, PID3) "

So the query becomes: 所以查询变成:

t2 <- sqlquery(db2,paste0("select * from table2 where [Serial no] IN (",paste(r1,collapse=", "),") ",sep =""))

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM