Postgresql
遍歷 Postgres 列舉值?
我有一個 Postgres 列舉類型,用於描述源/目標關係表的節點類(順序敏感)。問題是,如何動態獲取列舉實例的下一個值(如果有)?
CREATE TYPE MyEnum AS ENUM ('level1', 'level2', 'level3'); SELECT dst_type, dst_id FROM my_relationships WHERE src_type::MyEnum = next(dst_type::MyEnum) -- does not work -- WHERE src_type::MyEnum = dst_type::MyEnum + 1 -- does not work AND src_id = 'd4fc1d5d-b054-d37c-4e80-2c04a6b3dbf8';
我不認為有任何內置的,但你可以編寫函式來做到這一點:
create function next_enum(p_current myenum) returns myenum as $$ select t.name from unnest(enum_range(NULL::myenum)) with ordinality as t(name,idx) where name > p_current order by idx limit 1; $$ language sql stable;
那麼這應該工作:
SELECT dst_type, dst_id FROM my_relationships WHERE src_type = next_enum(dst_type) AND src_id = 'd4fc1d5d-b054-d37c-4e80-2c04a6b3dbf8';