【问题标题】:Compound foreign key constraint with a String literal带有字符串文字的复合外键约束
【发布时间】:2017-10-09 09:22:10
【问题描述】:

我有一个带有复合主键的表:

Table "account.enum"
Column   |          Type          | Modifiers
-----------+------------------------+-----------
classname | character varying(256) | not null
name      | character varying(64)  | not null
active    | boolean                | not null
Indexes: "enum_pkey" PRIMARY KEY, btree (classname, name)

价值观:

classname   |  name  | active
--------------+--------+--------
CURRENCY     | EUR    | t
CURRENCY     | USD    | t
MUTATIONTYPE | CREDIT | t
MUTATIONTYPE | DEBET  | t

另一个表帐户使用此表:

Table "account.mutation"
Column      |          Type          |                       Modifiers
-----------------+------------------------+-------------------------------------------------------
id              | bigint                 | not null default nextval('mutation_id_seq'::regclass)
accountnumber   | character varying(9)   | not null
interestdate    | date                   | not null
balancebefore   | numeric(10,2)          | not null
balanceafter    | numeric(10,2)          | not null
transactiondate | date                   | not null
amount          | numeric(10,2)          | not null
description     | character varying(512) | not null
ordernumber     | smallint               | default (-1)
mutationtype    | character varying(64)  |
currency        | character varying(64)  |

我想添加外键约束(针对突变类型和货币):

alter table mutation add constraint FK_mutationtype foreign key('MUTATIONTYPE', mutationtype) references enum(classname, name);
alter table mutation add constraint FK_currency     foreign key('CURRENCY', currency)         references enum(classname, name);

但是不接受字符串文字。 我究竟做错了什么?我想在 postgres 中实现吗?

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    您不能这样做,因为外键只能在列上定义,而不能在像文字 'MUTATIONTYPE' 这样的表达式上定义。

    您可以在mutation 中引入像mutation_class 这样的列,该列始终设置为'MUTATIONTYPE',但这听起来很浪费、多余和愚蠢。

    我认为你应该通过为不同的枚举设置不同的查找表来解决问题,那么困难就会消失,从关系的角度来看,整个设计看起来更合理。

    【讨论】:

    • 感谢您的意见。这意味着我应该为我介绍的每个枚举创建一个新表。由于所有这些表都相似,我正在寻找一个单一的表解决方案。
    • 单表有什么好处?
    • 如果Java代码中有新的枚举或枚举常量,Java会自动填充枚举表。我不想每次创建或修改 Java 枚举类时都创建(flyway)SQL 脚本。
    • 您不能编写 Java 代码以使其使用不同的表?
    • 我会试试的。谢谢。
    猜你喜欢
    • 2017-03-25
    • 2012-04-27
    • 2019-08-26
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多