【问题标题】:Searching through all columns in a table搜索表中的所有列
【发布时间】:2016-06-15 23:18:42
【问题描述】:

我有一个包含 300 多列的表,其中许多列中没有数据。是否有一个查询可以用来找出这些列的名称,以便我可以从表中删除它们。如果这很重要,我也在 Redshift 服务器上使用 postgresql 数据库

【问题讨论】:

    标签: sql postgresql search null


    【解决方案1】:

    您可以尝试使用jsonb typefunctions

    假设您的表声明为

    create table t as (x int, y varchar, z numeric);
    

    首先让我们将表格的行转换为 jsonb。很简单:

    select to_jsonb(t.*) from t;
    

    结果(用于测试数据)

             to_jsonb          
    --------------------------
     {"x":1,"y":"a","z":null}
     {"x":2,"y":"b","z":null}
    

    接下来,我们将使用另一个 json 函数将这些结果转换为 (key,value) 之类的行:

    select jsonb_each(to_jsonb(t.*)) from t;
    

    结果:

      jsonb_each  
    -------------
     (x,1)
     (y,"""a""")
     (z,null)
     (x,2)
     (y,"""b""")
     (z,null)
    

    这几乎是我们所需要的。下一步:

    select (w).key, (w).value from (select jsonb_each(to_jsonb(t.*)) as w from t) tt;
    

    结果

     key | value 
    -----+-------
     x   | 1
     y   | "a"
     z   | null
     x   | 2
     y   | "b"
     z   | null
    

    这里我们使用(w)来指定它是字段而不是表。

    最后一步:

    select 
      (w).key 
    from 
      (select jsonb_each(to_jsonb(t.*)) as w from t) tt 
    group by 
      (w).key 
    having 
      count(*) filter (where((w).value != 'null')) = 0;
    

    结果

     key 
    -----
     z
    

    尝试使用最后一个查询,将t 替换为您的表名。


    更新:

    您也可以尝试使用 PostgreSQL 统计信息:

    analyse yourtable;
    
    select
      pg_class.relname,
      pg_attribute.attname,
      pg_statistic.stanullfrac
    from
      pg_class join
        pg_statistic on (pg_class.oid = pg_statistic.starelid) join
          pg_attribute on (pg_class.oid = pg_attribute.attrelid and pg_statistic.staattnum = pg_attribute.attnum)
    where
      pg_class.relname = 'yourtable';
    

    stanullfrac 列中,您将看到每个表列的空值的相对数量,其中 1 表示所有空值(但我不确定它的准确性)

    【讨论】:

      【解决方案2】:

      首先你得到字段名

      SELECT *
      FROM information_schema.columns
      WHERE table_schema = 'your_schema'
        AND table_name   = 'your_schema'
      

      然后使用循环创建动态查询

      SELECT count(*)
      FROM 'your_schema'.'your_schema'
      WHERE `yourfield` IS NOT NULL
      HAVING count(*) = 0
      

      Using a cursor with dynamic SQL in a stored procedure

      【讨论】:

      • 我理解第一部分并且已经做到了,动态查询是我被卡住了。除了第一步之外,我不知道该怎么做 'yourfield' 来自什么?
      • 你创建一个游标,为游标循环,用你想要的查询构建一个字符串strSQLexecute strSQL 我包含示例的链接
      • 好的,我很抱歉,但这对我来说仍然没有意义,您能否将脚本写在一页而不是提供其他问题的链接?
      • 对不起,我不会再写那个解释了。他已经花了很多时间给出一个很好的解释。如果你害怕这个链接,那只是这个论坛中另一个问题的链接
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 2014-02-14
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多