簡體   English   中英

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

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

我有兩張桌子; viz table1 = PID(主鍵)+ 20個其他列&200個記錄來自database1 AND table2 = [Serial no](主鍵)+10個其他列&300個記錄來自database2。

我試圖從table2中提取值,其中PID = [Serial no]。

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

我提到“在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 ="")

我還嘗試了其他函數viz paste0(),fn $來自gsubfn和sprintf()並得到錯誤 - 'c不是公認的內置函數名'; '語法不正確'。

請建議最好的方法。

注冊,

Mrutyunjaya

您的查詢已關閉。 請參閱此處了解適當的格式。

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

錯誤

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

輸出:

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

正確

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

輸出:

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

所以查詢變成:

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

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM