dbplyr:合并两个表并将结果添加到数据库而不将它们加载到内存中
Dbplyr: combine two tables and add the to the result to the database without loading them in memory
请看一下post末尾的简单脚本。
我有一个包含两个表的数据库,我使用 union_all 组合它们。
有没有办法将结果添加到数据库而不收集数据,即将它们加载到内存中?
非常感谢!
library(tidyverse)
library(DBI) # main DB interface
library(dbplyr) # dplyr back-end for DBs
#>
#> Attaching package: 'dbplyr'
#> The following objects are masked from 'package:dplyr':
#>
#> ident, sql
library(RSQLite)
##create the databases
df1 <- tibble(x=1:20,y=rep(c("a", "b"), 10))
df2 <- tibble(x=101:120,y=rep(c("d", "e"), 10))
con <- dbConnect(drv=RSQLite::SQLite(), dbname="db.sqlite")
dbWriteTable(con,"mydata1",df1, overwrite=T)
dbWriteTable(con,"mydata2",df2, overwrite=T)
dbDisconnect(con) # closes our DB connection
con <- dbConnect(drv=RSQLite::SQLite(), dbname="db.sqlite")
mydb1 <- tbl(con, "mydata1")
mydb2 <- tbl(con, "mydata2")
mydb12 <- union_all(mydb1,mydb2)
#is there a way to add the union of mydb1 and mydb2 to the database without explicitly collecting the data?
由 reprex package (v0.3.0)
于 2020-12-24 创建
由于您要处理 SQL,只需使用 SQL。
collect(mydb1) %>%
nrow()
# [1] 20
DBI::dbExecute(con, "insert into mydata1 select * from mydata2")
# [1] 20
collect(mydb1) %>%
nrow()
# [1] 40
collect(mydb1) %>%
tail()
# # A tibble: 6 x 2
# x y
# <int> <chr>
# 1 115 d
# 2 116 e
# 3 117 d
# 4 118 e
# 5 119 d
# 6 120 e
如果您想要在新的 table 中合并数据,那么这里有一个替代方案。
DBI::dbExecute(con, "
create table mydata12 as
select * from mydata2 union all select * from mydata1")
请看一下post末尾的简单脚本。 我有一个包含两个表的数据库,我使用 union_all 组合它们。 有没有办法将结果添加到数据库而不收集数据,即将它们加载到内存中? 非常感谢!
library(tidyverse)
library(DBI) # main DB interface
library(dbplyr) # dplyr back-end for DBs
#>
#> Attaching package: 'dbplyr'
#> The following objects are masked from 'package:dplyr':
#>
#> ident, sql
library(RSQLite)
##create the databases
df1 <- tibble(x=1:20,y=rep(c("a", "b"), 10))
df2 <- tibble(x=101:120,y=rep(c("d", "e"), 10))
con <- dbConnect(drv=RSQLite::SQLite(), dbname="db.sqlite")
dbWriteTable(con,"mydata1",df1, overwrite=T)
dbWriteTable(con,"mydata2",df2, overwrite=T)
dbDisconnect(con) # closes our DB connection
con <- dbConnect(drv=RSQLite::SQLite(), dbname="db.sqlite")
mydb1 <- tbl(con, "mydata1")
mydb2 <- tbl(con, "mydata2")
mydb12 <- union_all(mydb1,mydb2)
#is there a way to add the union of mydb1 and mydb2 to the database without explicitly collecting the data?
由 reprex package (v0.3.0)
于 2020-12-24 创建由于您要处理 SQL,只需使用 SQL。
collect(mydb1) %>%
nrow()
# [1] 20
DBI::dbExecute(con, "insert into mydata1 select * from mydata2")
# [1] 20
collect(mydb1) %>%
nrow()
# [1] 40
collect(mydb1) %>%
tail()
# # A tibble: 6 x 2
# x y
# <int> <chr>
# 1 115 d
# 2 116 e
# 3 117 d
# 4 118 e
# 5 119 d
# 6 120 e
如果您想要在新的 table 中合并数据,那么这里有一个替代方案。
DBI::dbExecute(con, "
create table mydata12 as
select * from mydata2 union all select * from mydata1")