【发布时间】:2020-12-22 14:58:06
【问题描述】:
亲爱的,
我快到了,但我不能多走一英里。 我需要做一些简单的事情:bind_row 来自两个数据库的两个表。请看一下这个简单的reprex
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))
con1 <- dbConnect(drv=RSQLite::SQLite(), dbname="db1.sqlite")
dbWriteTable(con1,"mydata",df1, overwrite=T)
dbDisconnect(con1) # closes our DB connection
con2 <- dbConnect(drv=RSQLite::SQLite(), dbname="db2.sqlite")
dbWriteTable(con2,"mydata",df2, overwrite=T)
dbDisconnect(con2) # closes our DB connection
#### Now read the databases and use union_all to bind the rows of their table
con <- dbConnect(drv=RSQLite::SQLite(), dbname="db1.sqlite")
db1 <- tbl(con, "mydata")
db1
#> # Source: table<mydata> [?? x 2]
#> # Database: sqlite 3.33.0 [/tmp/RtmpIk3vcV/reprex23781b78632e/db1.sqlite]
#> x y
#> <int> <chr>
#> 1 1 a
#> 2 2 b
#> 3 3 a
#> 4 4 b
#> 5 5 a
#> 6 6 b
#> 7 7 a
#> 8 8 b
#> 9 9 a
#> 10 10 b
#> # … with more rows
con <- dbConnect(drv=RSQLite::SQLite(), dbname="db2.sqlite")
db2 <- tbl(con,"mydata")
db2
#> # Source: table<mydata> [?? x 2]
#> # Database: sqlite 3.33.0 [/tmp/RtmpIk3vcV/reprex23781b78632e/db2.sqlite]
#> x y
#> <int> <chr>
#> 1 101 d
#> 2 102 e
#> 3 103 d
#> 4 104 e
#> 5 105 d
#> 6 106 e
#> 7 107 d
#> 8 108 e
#> 9 109 d
#> 10 110 e
#> # … with more rows
db12 <- union_all(db1, db2)
#> Error: `x` and `y` must share the same src, set `copy` = TRUE (may be slow).
由reprex package (v0.3.0) 于 2020 年 12 月 22 日创建
失败是因为(至少我认为)我应该为 db1 和 db2 使用相同的连接对象,请参阅
https://github.com/r-dbi/bigrquery/issues/219
但我不能把它做好。解决方案必须是单行的,任何帮助表示赞赏! 谢谢!
【问题讨论】: