首页 > 解决方案 > 在 Redshift 中查找具有特定值的单元格的脚本

问题描述

我有这个查询:

    select t.table_schema,
       t.table_name,
       c.column_name
from information_schema.tables t
inner join information_schema.columns c
           on c.table_name = t.table_name
           and c.table_schema = t.table_schema
where c.column_name like '%column_name%'
      and t.table_schema not in ('information_schema', 'pg_catalog')
      and t.table_type = 'BASE TABLE'
order by t.table_schema;

有没有什么地方我可以实际搜索特定值并查看它属于哪个列、表和架构?

例如,我想搜索一个值“WINNER”并找出哪些列包含该值(显然还有表和架构),并且该列可能是 STATUS,值为 WINNER,在表 CUSTOMER 和架构 ALL_DATA 下

有人可以帮忙吗?

标签: sqlamazon-redshift

解决方案


没有直接的方法可以做到这一点,据我所知,任何 DBMS 中都没有内置功能。如何做到这一点的一种方法是创建选择所有类似文本的列并生成另一个 SQL 的 SQL。有一个例子:

select 'select '''||t.table_schema||''' as table_schema, '''||
   t.table_name||''' as table_name, '''||
   c.column_name||''' as column_name,'||
   ' count(*) as occurrences'
   ' from '||t.table_schema||'.'||t.table_name||
   ' where '||c.column_name||' like ''WINNER'''
   ||' union all '
from information_schema.tables t
inner join information_schema.columns c
           on c.table_name = t.table_name
           and c.table_schema = t.table_schema
where c.column_name like '%column_name%'
      and t.table_schema not in ('information_schema', 'pg_catalog')
      and t.table_type = 'BASE TABLE'
      and c.data_type = 'character varying'
order by t.table_schema;

根据查询中设置的限制,它将生成与您要搜索的列一样多的行。将此结果块复制到您的客户端(从最后一行删除“union all”) 并执行。尽量限制行数以获得更好的性能。由于列数据存储 Redshift 将非常有效地执行此操作,请记住,在面向行的 DBMS 上,这种方法的性能会更差。


推荐阅读