列出Postgres ENUM类型


100

建议查询列表ENUM类型是伟大的。但是,它仅列出了schematypname。如何列出实际的ENUM值?例如,在上面的链接答案中,我想要以下结果

schema         type      values
-------------  --------  -------
communication  channels  'text_message','email','phone_call','broadcast'

Answers:


134
select n.nspname as enum_schema,  
       t.typname as enum_name,  
       e.enumlabel as enum_value
from pg_type t 
   join pg_enum e on t.oid = e.enumtypid  
   join pg_catalog.pg_namespace n ON n.oid = t.typnamespace

4
甜...甚至更好的使用string_agg(e.enumlabel, ', ') as enum_value与适当的GROUP BYs。非常感谢。
庞克

4
这是荒唐的。为什么地球上没有速记?(不过,感谢您的解决方案!)
dbb 2015年



15

我总是忘记该怎么做。根据其他答案和评论,这是一个逗号分隔的列表。我喜欢复制粘贴的片段。谢谢您的帮助:

select n.nspname as enum_schema,  
    t.typname as enum_name,
    string_agg(e.enumlabel, ', ') as enum_value
from pg_type t 
    join pg_enum e on t.oid = e.enumtypid  
    join pg_catalog.pg_namespace n ON n.oid = t.typnamespace
group by enum_schema, enum_name;


0

@dpb:

如果要为此创建永久的便捷访问方法,则可以始终创建视图

CREATE OR REPLACE VIEW oublic.enumz AS 
 SELECT n.nspname AS enum_schema,
  t.typname AS enum_name,
  e.enumlabel AS enum_value
 FROM pg_type t
 JOIN pg_enum e ON t.oid = e.enumtypid
 JOIN pg_namespace n ON n.oid = t.typnamespace;

然后,您可以为insert命令创建触发器。

上面将把它存储在数据库中,以备将来参考。


0

这列出了所有枚举类型的及其潜在值:

SELECT
  table_schema || '.' || table_name || '.' || column_name as field_name,
  pg_enum.enumlabel as value
FROM pg_type
  JOIN pg_enum ON pg_enum.enumtypid = pg_type.oid
  JOIN pg_namespace on pg_type.typnamespace = pg_namespace.oid
  JOIN information_schema.columns ON (information_schema.columns.udt_name = pg_type.typname AND information_schema.columns.udt_schema = pg_namespace.nspname)
WHERE pg_type.typtype = 'e'
ORDER BY field_name, pg_enum.enumsortorder;

0

新增订单

SELECT
  n.nspname AS enum_schema,
  t.typname AS enum_name,
  e.enumlabel AS enum_value
FROM
  pg_type t
  JOIN pg_enum e ON t.oid = e.enumtypid
  JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
ORDER BY
  enum_name,
  e.enumsortorder;

-2

如果您具有表名和列名(但没有类型名),请使用以下命令:

SELECT pg_enum.enumlabel
FROM pg_type
 JOIN pg_enum ON pg_enum.enumtypid = pg_type.oid
 JOIN information_schema.columns ON information_schema.columns.udt_name =
                                    pg_type.typname
WHERE pg_type.typtype = 'e' AND
      table_name = $1 AND column_name = $2 ORDER BY pg_enum.enumsortorder

如果enum_range在列上使用(与在类型上使用它的其他答案相反),它将为存在的每一行返回数据,这不是您想要的。因此,请改用上述查询。


1
由于您未加入pg_namespace,因此如果在多个模式中存在相同的枚举名称,则会导致错误的关联...
blubb
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.