我有一个用新表更新的redshift数据库,所以我不能只是手动列出想要的表。我想从查询中获取所有表的行数。到目前为止,我有:
select 'SELECT ''' || table_name || ''' as table_name, count(*) As con ' ||
'FROM ' || table_name ||
CASE WHEN lead(table_name) OVER (order by table_name ) IS NOT NULL
THEN ' UNION ALL ' END
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%results%'
但是当我这样做时,我得到了错误:
Specified types or functions (one per INFO message) not supported on Redshift tables.
我进行了很多搜索,但似乎找不到解决我问题的方法。任何帮助将不胜感激。谢谢!
编辑: 我已经改变了方法,决定在R中使用for循环来获取每个行的计数,但是我遇到了一个问题,即“ row_counts”仅保存一个数字,而不是像我这样保存每行的计数想。这是代码:
schema <- "x"
table_prefix <- "results"
geos <- ad_districts %>% filter(geo != "geo")
row_count <- list()
i = 1
for (geo in geos){
table_name <- paste0(schema, ".", table_prefix, geo)
row_count[[i]] <- dbGetQuery(con,
paste("SELECT COUNT(*) FROM", table_name))
i = i + 1
}
答案 0 :(得分:0)
[EDIT]-我认为这是根本原因-某些SQL函数仅在Leader节点上受支持。尝试连接到该节点并重新运行SQL。 https://docs.aws.amazon.com/redshift/latest/dg/c_sql-functions-leader-node.html
希望这会有所帮助。
select 'select count(*) as "' || table_schema || '.' || table_name || '" from ' || table_schema || '.' || table_name || ' ;' as sql_text
from information_schema.tables
;
[编辑-对此进行了一些改进,以生成可以立即运行的一系列语句]
select rownum, case when rownum > 1 then sql_text else replace(sql_text, 'union all', '') end as sql_text
from
(
select rank() over (order by sql_text DESC) as rownum,
sql_text
from
(
select 'select ''' || table_schema || ' ' || table_name || ''' , count(*) as "' || table_schema || '.' || table_name || '" from ' || table_schema || '.' || table_name || ' union all ' as sql_text
from information_schema.tables
where table_schema = 'public'
order by table_schema, table_name
)X
)Y
order by rownum desc ;
答案 1 :(得分:0)
您的查询正在为所有表执行select *,这将花费大量时间和资源。而是使用系统表获取相同的信息
select name, sum(rows) as rows
from stv_tbl_perm
where name like '%results%'
group by 1
答案 2 :(得分:0)
SELECT ' Select count(*) , '''+ tablename + ''' from '+'"' + tablename +'"' +' Union ALL '
FROM pg_table_def
GROUP BY tablename
以上查询消除了带空格的任何表名。在查询结束时删除UNION ALL,即可开始执行查询。