如何使用R连接数据库

时间:2016-11-21 16:07:23

标签: sql r database

我在使用sqlQuery将数据库与R连接时遇到问题。

library(RODBC)
res =sqlQuery(channel,
    paste0("select pb.col1,pb.col2 from pb,
                   mp,fb,st 
            where fb.col10 in ('%s',input), 
            and fb.col20=mp.col30 
            and pb.col40=st.col50 
            and pb.col45=st.col60 
            and mp.col40=pb.col80 and 
            pb.col80=st.col90"),
         believeNRows=F)

此处为input=c("abc","def","wvy","etz"),但实际输入的字符串元素超过10,000个。

频道已设置为与数据库连接。

看起来where子句存在一些问题,但我不知道如何修复它。

任何人都可以帮我吗?

1 个答案:

答案 0 :(得分:1)

paste0无法按照您使用它的方式运行。你需要使用:

sprintf("select pb.col1,pb.col2 
         from pb,mp,fb,st 
            where fb.col10 in %s 
            and fb.col20=mp.col30 
            and pb.col40=st.col50 
            and pb.col45=st.col60 
            and mp.col40=pb.col80 and 
            pb.col80=st.col90", input)

接下来,这种结构化的方式将导致query参数成为向量。您的目标应该是query为单个字符串。

使用RODBCext

可能会更好
library(RODBCext)
res =sqlExecute(channel,
              "select pb.col1,pb.col2 
               from pb,mp,fb,st 
               where fb.col10 in ?, 
                  and fb.col20=mp.col30 
                  and pb.col40=st.col50 
                  and pb.col45=st.col60 
                  and mp.col40=pb.col80 
                  and pb.col80=st.col90",
              data = list(c("abc", "def", "wvy", "etz")),
              fetch = TRUE,
              stringsAsFactors = FALSE)

最后,我不确定此查询是否是有效的SQL语法。也许我错了,但我不认为你可以在FROM子句中列出多个表,就像你在这里一样。如果你需要多个表,应该有一些方法可以加入它们。

FROM Table1 LEFT JOIN Table2 ON Table1.ID = Table2.Ref
编辑:我刚看到你的input有超过10,000个元素,这会使sqlExecute变得非常缓慢。您确定LIKE是查询这些数据的最佳方式。如果可能的话,我会建议其他方法来隔离你需要的数据。