How to pass data.frame into SQL “IN” condition using R?

前端 未结 1 1973
眼角桃花
眼角桃花 2021-01-28 13:58

I am reading list of values from CSV file in R, and trying to pass the values into IN condition of SQL(dbGetQuery). Can some one help me out with this?

library(r         


        
相关标签:
1条回答
  • 2021-01-28 14:14

    The SQL code you pass in the second argument to dbGetQuery is just a text string, hence you can construct this using paste or equivalents.

    You are after something like the following:

    in_clause <- paste0("('", paste0(pii$PII_ID, collapse = "', '"), "')")
    
    sql_text <- paste0("SELECT ARTICLE_ID 
                  FROM JRBI_OWNER.JRBI_ARTICLE_DIM
                  WHERE PII_ID IN ", in_clause)
    
     data <- dbGetQuery(jdbcConnection, sql_text)
    

    However, the exact form of the first paste0 depends on the format of PII_ID (I have assumed it is text) and how this format is represented in sql (I have assumed single quotes).

    Be sure to check sql_text is valid SQL before passing it to dbGetQuery.

    IMPORTANT: This approach is only suitable when pii contains a small number of values (I recommend fewer than 10). If pii contains a large number of values your query will be very large and will run very slowly. If you have many values in pii then a better approach would be a join or semi-join as per @nicola's comment.

    0 讨论(0)
提交回复
热议问题