如何在 R 中访问和阅读 Postgres 视图

How to access and read Postgres views in R

我正在尝试访问和读取 R 中 Postgres 数据库的表和视图。我能够使用 RPostgres 包使用 dbListTables 函数获取表,但面临 [=14= 的问题].

由于对 postgres 的知识还很幼稚,因此也在寻找访问和阅读 R 中视图的方法。

library(RPostgres)
library(DBI)
library(dplyr)
library(sqldf)

pw<- {
"password"
}

conn <- dbConnect(RPostgres::Postgres()
             , host="host-name"
             , port='5432'
             , dbname="database-name"
             , user="username"
             , password=pw)

dbExistsTable(conn, "Test_Table")
#TRUE
dbListTables(conn)

mydf <- dbReadTable(conn, "Test_Table") # To Read the table in R

我也按照 link 尝试了以下命令:https://github.com/tidyverse/dplyr/issues/1007 但没有成功。

SELECT table_name
FROM INFORMATION_SCHEMA.tables 
WHERE table_schema = ANY (current_schemas(false));  

dbExistsTabledbListTables 似乎看不到 Postgres 视图。

但是您应该可以通过这样的查询找到它们:

SELECT table_schema, table_name
FROM information_schema.tables
WHERE table_schema not in ('pg_catalog', 'information_schema') and table_type = 'VIEW'

一旦您知道要查找的视图的名称,dbReadTable(conn, "myview") 就可以了。

注意:如果仍然不起作用,请确保使用

设置正确的架构
SET search_path to myschema

确保视图名称在引号中。

viewDataFrame<-dbGetQuery(con,'SELECT * FROM dh2."viewName"')

注意:视图名称 "viewName" 在引号中。否则它不会工作。