如何从R中的数据库获取列名?

时间:2018-11-12 12:10:04

标签: r database rpostgresql

如何使用R获取唯一的特定表列名称?

示例代码:

df<-dbgetQuery(con,"select * from table 1 limit 100")
colnames(df)

上述查询是否还有其他选择?

2 个答案:

答案 0 :(得分:1)

得到解决方案,并使用以下查询获取名称。

dbGetQuery(con,"SELECT column_name
+ FROM information_schema.columns
+ WHERE table_schema = 'your schema'
+   AND table_name   = 'table name'") ##ORDER  BY ordinal_position; to orderby

示例查询:

dbGetQuery(con,"SELECT column_name, data_type
+ FROM   information_schema.columns
+ WHERE  table_name = 'data 1'
+ ORDER  BY ordinal_position")

两个查询都运行良好。

答案 1 :(得分:0)

为了完整起见,我发布了用于检索表概览+具有类型的表列概览的完整代码:

library(RPostgres)

# login
your_connection <- dbConnect(Postgres(),
                             host = '*your-host-address*',
                             port = *your-port-four-digits*,
                             user = '*your-username*',
                             password = 'your-password*',
                             sslmode = 'require',
                             dbname = '*name-of-database*')

# send request to get overview of tables
res <- dbSendQuery(your_connection, "select distinct table_schema
                   from information_schema.tables
                   where table_type ='VIEW'
                   or table_type ='FOREIGN TABLE'
                   order by table_schema")
data <- dbFetch(res, n=-1)
dbClearResult(res)
data

# send request to get overview of tables in a table schema
res <- dbSendQuery(your_connection, "select distinct table_name
                   from information_schema.columns
                   where table_schema='*your-table-name*'
                   order by table_name")
data <- dbFetch(res, n=-1)
dbClearResult(res)
data

# send request to get overview of columns of a table
res <- dbSendQuery(your_connection, "select distinct column_name, data_type
                   from information_schema.columns
                   where table_name ='*your-table-name*'
                   order by column_name")
data <- dbFetch(res, n=-1)
dbClearResult(res)
data