【发布时间】:2016-06-15 23:18:42
【问题描述】:
我有一个包含 300 多列的表,其中许多列中没有数据。是否有一个查询可以用来找出这些列的名称,以便我可以从表中删除它们。如果这很重要,我也在 Redshift 服务器上使用 postgresql 数据库
【问题讨论】:
标签: sql postgresql search null
我有一个包含 300 多列的表,其中许多列中没有数据。是否有一个查询可以用来找出这些列的名称,以便我可以从表中删除它们。如果这很重要,我也在 Redshift 服务器上使用 postgresql 数据库
【问题讨论】:
标签: sql postgresql search null
您可以尝试使用jsonb type 和functions。
假设您的表声明为
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 表示所有空值(但我不确定它的准确性)
【讨论】:
首先你得到字段名
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
【讨论】:
strSQL 和execute strSQL 我包含示例的链接