根据应用程序中的用户输入创建动态SQL查询

根据应用程序中的用户输入创建动态SQL查询,sql,r,sqlite,shiny,rsqlite,Sql,R,Sqlite,Shiny,Rsqlite,我有一个闪亮的应用程序,用户可以过滤电影的SQL数据库。到目前为止,您只能按不同的国家筛选 con <- dbConnect(RSQLite::SQLite(), 'Movies.db') movies_data <- dbReadTable(con, 'Movies') ui <- fluidPage( fluidRow( selectInput( inputId = "country", label = "

我有一个闪亮的应用程序,用户可以过滤电影的SQL数据库。到目前为止,您只能按不同的国家筛选

con <- dbConnect(RSQLite::SQLite(), 'Movies.db')
movies_data <- dbReadTable(con, 'Movies')

ui <- fluidPage(
  fluidRow(
    selectInput(
      inputId = "country",
      label = "Country:",
      choices = movies_data$journal,
      multi=T
    ),
    br(),
    fluidRow(width="100%",
           dataTableOutput("table")
    )
  )
)

server <- function(input, output, session) {
        
  output$table <- renderDataTable({
    dbGetQuery(
      conn = con,
      statement = 'SELECT * FROM movies WHERE country IN ( ? )',
      params = list(input$country))
  })
}
shinyApp(ui = ui, server = server)

现在我想给用户更多的过滤器,例如演员或流派。所有过滤器都是多选和可选的。如何创建动态语句?我是否会对每种可能的组合使用一些切换语句,即不过滤国家/地区,而只过滤动作片?这似乎有点让我筋疲力尽。

首先,你说过滤器是可选的,但我认为没有办法在你的代码中禁用它。我假设取消选择所有选项是您禁用过滤器的方式,或者至少它打算以这种方式工作。如果为任何滤镜选择了所有选项,那么当前方法应该可以正常工作,并且只显示所有胶片

您可能只需逐段构建整个查询,然后在最后将其全部粘贴在一起

基本查询:“从电影中选择*”

国家/地区筛选器:“国家/地区在”输入国家/地区

参与者筛选器:“参与者中的参与者”输入参与者

流派过滤器:“流派中的流派”输入流派

然后你把它和浆糊放在一起

总结:基本查询。然后,如果任何过滤器处于活动状态,则添加一个WHERE。将所有过滤器连接在一起,以和分隔。将最终查询作为直接字符串传入

您甚至可以将过滤器放入列表中,以便于解析

# Here, filterList is a list containing input$country, input$actor, input$genre
# and filterNames contains the corresponding names in the database
# e.g. filterList <- list("c1", list("a1", "a2"), "g1")
# filterNames <- filterNames <- list("c", "a", "g")

baseQuery <- "SELECT * FROM movies"

# If any of the filters have greater than 0 value, this knows to do the filters
filterCheck <- any(sapply(filterList, length)>0)

# NOTE: If you have a different selection available for None
# just modify the sapply function accordingly

if(filterCheck)
{
  baseQuery <- paste(baseQuery, "WHERE")

  # This collapses multiselects for a filter into a single string with a comma separator
  filterList <- sapply(filterList, paste, collapse = ", ")

  # Now you construct the filters
  filterList <- sapply(1:length(filterList), function(x)
    paste0(filterNames[x], " IN (", filterList[x], ")"))

  # Paste the filters together
  filterList <- paste(filterList, collapse = " and ")

  baseQuery <- paste(baseQuery, filterList)
}

# Final output using the sample input above:
# "SELECT * FROM movies WHERE c IN (c1) and a IN (a1, a2) and g IN (g1)"

现在使用baseQuery作为直接查询语句

如果您已经在将整个数据库中的数据读入movies\u数据,为什么要尝试生成动态查询?我希望它会更快,因为它已经在内存中使用R过滤之类的。我看这并不理想。在最终产品中,我将使用其他方法填充inputselect。完整的数据非常大,所以我不想将所有内容都加载到内存中。我可能会用UNIQE在列表中选择电影名称。非常感谢!: