R 将 SQL 结果传递给 sql 语句

R passing SQL results to sql statement

我正在从 MySQL 数据库中提取一些结果,如下所示:

GetJobCodes=paste0("select EMPLID from jobCurrent where JOBCODE='",JOBCODE,"'")
JOBCODES = dbGetQuery(connection,GetJobCodes) 

我想将以上 JOBCODES 结果传递给其他 SQL 语句

statement=sprintf("SELECT A.EMPLID, A.CLASS_ID FROM lmsEnroll A JOIN lmsCourses\ 
              B ON A.COURSE_ID=B.COURSE_ID AND B.REQUIRED=0 WHERE A.EMPLID IN (%s)",JOBCODES)

但是当我传递给上面的语句时,它是打印的

SELECT A.EMPLID, A.CLASS_ID FROM lmsEnroll A JOIN lmsCourses\ 
       B ON A.COURSE_ID=B.COURSE_ID AND B.REQUIRED=0 WHERE A.EMPLID IN "C("00330022","00033322")")

这是不正确的,我想像这样打印它们:

SELECT A.EMPLID, A.CLASS_ID FROM lmsEnroll A JOIN lmsCourses\ 
       B ON A.COURSE_ID=B.COURSE_ID AND B.REQUIRED=0 WHERE A.EMPLID IN ("00330022","00033322")

我用过ShQuote函数,但没用。如果有人能帮助我,我将不胜感激。

您可以使用 glue 来执行此操作。

library(glue)

GetJobCodes <- paste0("select EMPLID from jobCurrent where JOBCODE='",JOBCODE,"'")
JOBCODES <- dbGetQuery(connection,GetJobCodes)
statement <- "SELECT A.EMPLID, A.CLASS_ID FROM lmsEnroll A JOIN lmsCourses\ 
              B ON A.COURSE_ID=B.COURSE_ID AND B.REQUIRED=0 WHERE A.EMPLID IN ({JOBCODES})"
request <- glue_sql(statement,JOBCODES = JOBCODES, .con = connection)

考虑一个带有参数化的查询(避免引用处理或连接),因为您可以在 IN 子句中使用 SELECT 语句:

sql <- "SELECT A.EMPLID, A.CLASS_ID 
        FROM lmsEnroll A 
        JOIN lmsCourses B ON A.COURSE_ID=B.COURSE_ID AND B.REQUIRED=0 
        WHERE A.EMPLID IN
           (SELECT EMPLID FROM jobCurrent WHERE JOBCODE = ?)"

emp_df <- dbGetQuery(connection, sql, list(JOBCODE)) 

或者,JOIN:

sql <- "SELECT A.EMPLID, A.CLASS_ID 
        FROM lmsEnroll A 
        INNER JOIN lmsCourses B 
              ON A.COURSE_ID = B.COURSE_ID AND B.REQUIRED = 0 
        INNER JOIN 
             (SELECT DISTINCT EMPLID FROM jobCurrent WHERE JOBCODE = ?) sub
              ON A.EMPLID IN sub.EMPLID"

emp_df <- dbGetQuery(connection, sql, list(JOBCODE))

知道了!这个问题都是关于渲染的事情。通过选择带有 JOBCODES 数据框的 EMPLID,问题得到了解决。

JOBCODES =paste(shQuote(JOBCODES$EMPLID,type="sh"),collapse=",") //Selecting EMPLID column

statement=paste0("SELECT A.EMPLID, A.CLASS_ID FROM lmsEnroll A JOIN lmsCourses B ON A.COURSE_ID=B.COURSE_ID AND B.REQUIRED=0 WHERE A.EMPLID IN 
(",JOBCODES,")")