create or replace function get_distinct_value(
name, -- schema
name, -- table
name -- column
) returns text as $$
declare
v int;
res text;
begin
select
case attstattarget
when -1 then current_setting('default_statistics_target')::int -- 默认bucket
else attstattarget -- 自定义bucket
end into v
from pg_attribute where attrelid=($1||'.'||$2)::regclass and attname=$3 ;
select (most_common_vals)::text into res -- 高频词
from pg_stats where not inherited and schemaname = $1 and tablename = $2 and attname = $3 and n_distinct >=1 and n_distinct <= v;
return res;
$$ language plpgsql strict;
postgres=# alter table tbl alter COLUMN c1 set statistics 300;
ALTER TABLE
postgres=# alter table tbl alter COLUMN c2 set statistics 300;
ALTER TABLE
重新分析表
postgres=# analyze tbl;
ANALYZE