2015-11-17 94 views
0

我有一個變量x,其中包含20000個ID。我想寫一個SQL查詢一樣,在R中的SQL查詢的「IN」函數中使用變量

select * from tablename where ID in x; 

我想實現這個R中,我能得到的值僅適用於變量x的ID。以下是我的嘗試,

dbSendQuery(mydb, "select * from tablename where ID in ('$x') ") 

我在嘗試此操作時沒有收到任何錯誤。但它返回0值。

下一頁使用

sprintf("select * from tablename where ID in %s",x) 

嘗試,但這一情況可能在DB代價高昂20000個個人查詢。

任何人都可以提出一種方法來編寫一個命令,它將通過x中的ID進行循環,並通過單個查詢保存到R中的Dataframe中?

回答

1

做如何粘貼:

dbSendQuery(mydb, paste("select * from tablename where ID in (", paste(x, collapse = ","), ")")) 
+0

非常感謝!這個工作正常。 – haimen

2

您需要在實際字符串中包含代碼。下面是我如何與gsub

x <- LETTERS[1:3] 

sql <- "select * from tablename where ID in X_ID_CODES " 

x_codes <- paste0("('", paste(x, collapse="','"), "')") 

sql <- gsub("X_ID_CODES", x_codes, sql) 

# see new output 
cat(sql) 
select * from tablename where ID in ('A','B','C') 


# then submit the query 
#dbSendQuery(mydb, sql) 
+0

這兩個代碼工作的罰款。由於這是一條線,更簡單的方法,我接受了。非常感謝 ! – haimen

+0

@haimen無論您的偏好如何。不過,請記住,如果您開始開發更復雜的需要動態的查詢。這些單行語句可能會非常笨拙。 – cdeterman