【问题标题】:How to tell PostgreSQL not to verify datatype如何告诉 PostgreSQL 不要验证数据类型
【发布时间】:2012-10-15 07:49:47
【问题描述】:

我有一张这样的桌子:

CREATE TABLE test(
id integer not null default nextval('test_id_seq'::regclass),
client_name_id integer not null
);

外键约束:

"test_client_name_id_fkey" FOREIGN KEY (client_name_id) REFERENCES company(id) DEFERRABLE INITIALLY DEFERRED

和公司表:

CREATE TABLE company(
id integer not null default nextval('company_id_seq'::regclass),
company_name character varying(64) not null
)

现在我在测试表上有触发器,它使用提供的值 client_name_id 从公司表中获取 id,该值是通过将其与 company_name 匹配的字符串。但是当我插入记录 PostgreSQL 时返回错误,client_name_id 是 string 并且 int required 这是真的。

我如何告诉 PostgreSQL 不要验证插入的行,因为我已经在触发器中处理了它。

【问题讨论】:

    标签: postgresql triggers insert foreign-keys postgresql-9.0


    【解决方案1】:

    您正在尝试做的事情非常不正统。你确定,这就是你想要的吗?当然,您不能在整数列中输入字符串(非数字)。这并不奇怪,对吧?如果您想改为输入文本,则必须改为添加一个文本列 - 如果您想匹配当前布局,则将 fk-constraint 限制为 company(company_name)

    ALTER TABLE test ALTER DROP COLUMN client_name_id; -- drops fk constraint, too
    ALTER TABLE test ADD COLUMN client_name REFERENCES company(company_name);
    

    您需要在 company.company_name 上设置一个 UNIQUE 约束才能允许这样做。

    但是,我建议您重新考虑您的方法。您的表格布局看起来很合适。触发器是非常规的元素。通常,您会引用主键,就像您现在拥有它一样。不需要触发器。要获取公司名称,您可以在SELECT 中加入表格:

    SELECT *
    FROM   test t
    JOIN   company c ON t.client_name_id = c.id;
    

    此外,这些非标准修饰符仅在您需要时才应存在:DEFERRABLE INITIALLY DEFERRED。例如,当您必须在表 test 中输入值之前,您必须在表 company 中输入引用值(在同一事务中)。

    【讨论】:

    • 我通过在查询中而不是在插入触发器中实现 FK 逻辑解决了这个问题
    猜你喜欢
    • 2020-02-09
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    • 2011-01-30
    • 1970-01-01
    • 2018-08-16
    • 2012-01-10
    相关资源
    最近更新 更多