使用R

时间:2017-05-01 14:37:55

标签: r postgresql

我使用R和RPostgreSQL包连接到PostgreSQL数据库。 db有许多模式,我想知道哪些表与特定模式相关联。

到目前为止,我已经尝试过:

dbListTables(db, schema="sch2014")
dbGetQuery(db, "dt sch2014.*")
dbGetQuery(db, "\dt sch2014.*")
dbGetQuery(db, "\\dt sch2014.*")

其中没有一个有效。

此相关问题也存在:Setting the schema name in postgres using R,它可以通过在连接处定义架构来解决问题。但是,它还没有得到答复!

3 个答案:

答案 0 :(得分:2)

阅读这个答案https://stackoverflow.com/a/15644435/2773500有帮助。我可以使用以下内容来获取与特定模式关联的表:

dbGetQuery(db,
           "SELECT table_name FROM information_schema.tables
                   WHERE table_schema='sch2014'")

答案 1 :(得分:1)

以下应该有效(使用 DBI_v1.1.1

DBI::dbListObjects(conn, DBI::Id(schema = 'schema_name'))

虽然它有你想要的所有信息,但很难访问和阅读。

我会推荐一些产生数据框的东西:

# get a hard to read table given some Postgres connection `conn`
x = DBI::dbListObjects(conn, DBI::Id(schema = 'schema_name'))

# - extract column "table" comprising a list of Formal class 'Id' objects then
# - extract the 'name' slot for each S4 object element
# could also do `lapply(d$table, function(x) x@name)`
v = lapply(x$table, function(x) slot(x, 'name'))

# create a dataframe with header 'schema', 'table'
d = as.data.frame(do.call(rbind, v))

或在一行中:

d = as.data.frame(do.call(rbind, lapply(DBI::dbListObjects(conn, DBI::Id(schema = 'schema_name'))$table, function(x) slot(x, 'name'))))

或者以更“整洁”的方式:

conn %>%
    DBI::dbListObjects(DBI::Id(schema = 'schema_name')) %>%
    dplyr::pull(table) %>%
    purrr::map(~slot(.x, 'name')) %>%
    dplyr::bind_rows()

输出类似于

> d
          schema     table
1    schema_name    mtcars

答案 2 :(得分:0)

您可以使用table_schema选项而不是仅使用架构来查看特定架构中的表列表。因此,与上面的示例代码段保持一致,以下行应该有效:

dbListTables(db, table_schema="sch2014")
相关问题