SQL查询以获取枚举可以具有的所有值 [英] SQL query to get all values a enum can have
问题描述
Postgresql在一段时间之前得到了枚举支持。
CREATE TYPE myenum AS ENUM(
'value1',
'value2',
);
如何使用查询获取枚举中指定的所有值?
如果你想要一个数组:
SELECT enum_range (NULL :: myenum)
如果要为枚举中的每个项目单独记录: p>
SELECT unnest(enum_range(NULL :: myenum))
附加信息
此解决方案正常工作,即使您的枚举是不在默认模式。例如,将 myenum
替换为 myschema.myenum
。
上述查询中返回的记录的数据类型将为 myenum
。取决于你在做什么,你可能需要转换为文本。例如
SELECT unnest(enum_range(NULL :: myenum)):: text
如果要指定列名,可以追加 AS my_col_name
。
感谢Justin Ohms指出了一些额外的提示,我将其纳入我的答案。 $ b
Postgresql got enum support some time ago.
CREATE TYPE myenum AS ENUM (
'value1',
'value2',
);
How do I get all values specified in the enum with a query?
If you want an array:
SELECT enum_range(NULL::myenum)
If you want a separate record for each item in the enum:
SELECT unnest(enum_range(NULL::myenum))
Additional Information
This solution works as expected even if your enum is not in the default schema. For example, replace myenum
with myschema.myenum
.
The data type of the returned records in the above query will be myenum
. Depending on what you are doing, you may need to cast to text. e.g.
SELECT unnest(enum_range(NULL::myenum))::text
If you want to specify the column name, you can append AS my_col_name
.
Credit to Justin Ohms for pointing out some additional tips, which I incorporated into my answer.
这篇关于SQL查询以获取枚举可以具有的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!