【问题标题】:Does Foreign Key constraint need to include NOT EQUAL to sibling Foreign Key?外键约束是否需要包含不等于兄弟外键?
【发布时间】:2013-11-25 23:31:56
【问题描述】:

我是 SQL 和 Postgresql 的新手。我试图更好地理解外键约束如何与父表的主键一起使用。

这是我目前对两张桌子的设置。我试图模仿一种 ISA 关系,其中 echecks IS-A 付款。

Table "public.payments"
Column |         Type          |                       Modifiers                        

pid    | integer               | not null default nextval('payments_pid_seq'::regclass)
street | character varying(80) | 
zip    | integer               | 
Indexes:
"payments_pkey" PRIMARY KEY, btree (pid)
Referenced by:
    TABLE "cards" CONSTRAINT "cards_pid_fkey" FOREIGN KEY (pid) REFERENCES payments(pid)
    TABLE "echecks" CONSTRAINT "echecks_pid_fkey" FOREIGN KEY (pid) REFERENCES payments(pid)


Table "public.echecks"
  Column   |         Type          | Modifiers 

rtgacctnum | bigint                | 
accttype   | character varying(80) | 
nameonacct | character varying(80) | 
pid        | integer               | not null default nextval('payments_pid_seq'::regclass)
Foreign-key constraints:
    "echecks_pid_fkey" FOREIGN KEY (pid) REFERENCES payments(pid)


Table "public.cards"
  Column   |         Type          |                      Modifiers                      
pid        | integer               | not null default nextval('cards_pid_seq'::regclass)
cnum       | bigint                | 
nameoncard | character varying(80) | 
Foreign-key constraints:
"cards_pid_fkey" FOREIGN KEY (pid) REFERENCES payments(pid)

使用当前的设置,我无法阻止 Echecks 和 Cards 从付款中继承相同的 pid。我希望 Echecks 使用 Payments 中的下一个可用 pid,在 Cards 中不是同一个 pid。

我希望发生的事情的简化版本:

Payments(pid, pay_type):
1, paypal
2, echeck
3, credit card
4, echeck

Echecks(fk_pid, acct_name)
2, susy
4, bob

Cards(fk_pid, card_name)
3, john

相反,Echecks 只是在插入时分配:

1, susy
2, bob

卡片分配:

1, john

在外键上设置约束以确保从 Payments 为其分配唯一 pid 的最佳方法是什么?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    Echecks 不会“获取”任何价值。你应该在其中插入一个你想出现在那里的值。所以你真正的问题在于你没有包含在你的帖子中的插入逻辑。

    【讨论】:

    • 是的,你是对的,我确实遗漏了那个重要的部分。因此,我希望能够INSERT INTO echecks(acctnum, type, nameonacct) VALUES (123456, 'checking' , 'susy'); 并使用来自 Payments 而不是在 Cards 中的正确唯一 pid 自动分配 pid。
    • FK 与值的自动插入没有任何关系。你不能指望它弄清楚,你必须告诉它该做什么。
    • @runit 但是 Payments 中的行会有什么?你必须在那里插入一些东西,对吧?查看有关如何同时插入两个具有 fk 引用的表的信息:depesz.com/2011/03/16/waiting-for-9-1-writable-cte
    猜你喜欢
    • 2021-02-10
    • 2010-11-24
    • 1970-01-01
    • 2013-02-04
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    相关资源
    最近更新 更多