有没有办法在 dbplyr inner_join SQL 翻译中添加 LIKE?

问题描述 投票:0回答:1

这是此问题的后续问题:如何使用前缀作为匹配来连接数据帧?

我在 SQL 服务器端有这两个表:

data <- memdb_frame(
  x = c("ANOTHER", "COMMON", "ZEBRA")
)

selection <- memdb_frame(
  x_prefix = c("ANO", "B", "CO"),
  type = c("One type", "Other type", "Other type")
)

我想加入它们并保留

x_prefix
x
前缀的行。

我正在尝试使用 dbplyr 构建适当的 SQL 查询,从这里开始:

inner_join(data, selection, by = c(x = "x_prefix")) |>
  show_query()

产生:

<SQL>
SELECT `x`, `type`
FROM `dbplyr_001` AS `LHS`
INNER JOIN `dbplyr_002` AS `RHS`
ON (`LHS`.`x` = `RHS`.`x_prefix`)

我需要的查询是:

<SQL>
SELECT `x`, `type`
FROM `dbplyr_001` AS `LHS`
INNER JOIN `dbplyr_002` AS `RHS`
ON (`LHS`.`x` LIKE `RHS`.`x_prefix` || '%')

我已经读过函数翻译小插图,但我仍然需要帮助。

sql r dplyr tidyverse dbplyr
1个回答
1
投票

如果您已经知道所需的特定 SQL 查询,那么在返回 dbplyr 操作之前直接执行它可能会更有效。

library(dbplyr)
library(dplyr)
library(DBI)
# Create a connection
con <- dbConnect(RSQLite::SQLite(), ":memory:")


copy_to(con,tibble(
  x = c("ANOTHER", "COMMON", "ZEBRA")
),name="d1")

copy_to(con,tibble(
  x_prefix = c("ANO", "B", "CO"),
  type = c("One type", "Other type", "Other type")
),name="selection")
 
dbExecute(conn=con,
           statement = "create table result as
           select x, type from d1 as LHS 
              inner join selection as RHS
               on (LHS.x LIKE RHS.x_prefix || '%')")
 
 
my_res_dtplyr_table <- tbl(con,"result") 

#dtplyering with the result
my_res_dtplyr_table |> select(type) 
my_res_dtplyr_table |> filter(x != "COMMON")
© www.soinside.com 2019 - 2024. All rights reserved.