简体   繁体   English

PostgreSQL 用户定义类型枚举与外键 - 维护和性能

[英]PostgreSQL user defined type enum vs foreign key - maintenance and performance

I am trying to decide between two approaches to user defined set of values for column in PostgreSQL table.我试图在 PostgreSQL 表中的列的用户定义值集的两种方法之间做出决定。

User defined data type:用户定义的数据类型:

CREATE TYPE track_class AS ENUM(
  'Easy', 'Medium', 'Difficult', 'Very difficult', 'NA'
);

Foreign key:外键:

CREATE TABLE track_class (
    class TEXT PRIMARY KEY
);

INSERT INTO track_class (class) VALUES ('Easy'), ('Medium'), ('Difficult'), ('Very difficult'), ('NA');

CREATE TABLE tracks (
    track_class TEXT REFERENCES track_class (class) ON UPDATE CASCADE
);

Is any one superior to the other from maintenance (add / edit / replace value to domain later) and/or performance (where, group by, order by) perspective talking about millions of records, or it does not make much difference?从维护(稍后向域添加/编辑/替换值)和/或性能(在哪里,分组,排序)角度谈论数百万条记录,是否有任何一个优于另一个,或者它没有太大区别?

I would not recommend using an enum.我不建议使用枚举。 Espacially deleting enum values is not possible without dropping the type.如果不删除类型,就不可能特别删除枚举值。

I guess very easy to handle and best in terms of modelling would be the new table with foreign key you mentioned.我想很容易处理并且在建模方面最好的是你提到的带有外键的新表。 Performance should be no problem here, if you put an index on the foreign-key-column.如果您在外键列上放置索引,性能应该没有问题。

Another option would be to use a CHECK -constraint:另一种选择是使用CHECK -约束:

ALTER TABLE mytable
    ADD CONSTRAINT myconstraint_only_some_values
        CHECK (mycolumn IN ('Easy', 'Medium', 'Difficult', 'Very difficult', 'NA'));

Perhaps this is more "visible" in your data and you don't have to think about joining.也许这在您的数据中更“可见”,您不必考虑加入。 If you do not forget the index on mycolumn , this version should be just as performant as the one with the foreign key.如果您没有忘记mycolumn上的索引,那么这个版本应该和带有外键的版本一样高效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM