簡體   English   中英

PostgreSQL,MonetDB和MySQL向現有表添加外鍵

[英]PostgreSQL, MonetDB and MySQL add foreign key to existing table

當我將外鍵添加到已經有數據的表中時,這些數據庫管理系統分別做什么?

他們是否分析列的每個值以確認它是來自引用表主鍵的值?

還是他們有其他一些優化的機制? 如果是這樣,那是什么機制?

我無法確認是否使用MonetDB,但是在PostgreSQL和MySQL(以及很可能也是在MonetDB上)中,答案是肯定的,如果鍵在引用表中不存在,它們將檢查每個值,並會引發錯誤。

請注意,被引用的列不必是被引用表的主鍵-您可以將任何列作為另一個表的外鍵進行引用。

是的,當然,沒有強制執行的約束是沒有意義的。 您可以嘗試一下(這是針對Postgres的):


DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;

CREATE TABLE one
        ( one_id SERIAL NOT NULL PRIMARY KEY
        , name varchar
        );
INSERT INTO one(name)
SELECT 'name_' || gs::text
FROM generate_series(1,10) gs ;

CREATE TABLE two
        ( two_id SERIAL NOT NULL PRIMARY KEY
        , one_id INTEGER -- REFERENCES one(one_id)
        );

INSERT INTO two(one_id)
SELECT one_id
FROM one ;

DELETE FROM one WHERE one_id%5=0;

ALTER TABLE two
        ADD FOREIGN KEY (one_id) REFERENCES one(one_id)
        ;

\d one
\d two

結果:


NOTICE:  drop cascades to 2 other objects
DETAIL:  drop cascades to table tmp.one
drop cascades to table tmp.two
DROP SCHEMA
CREATE SCHEMA
SET
CREATE TABLE
INSERT 0 10
CREATE TABLE
INSERT 0 10
DELETE 2
ERROR:  insert or update on table "two" violates foreign key constraint "two_one_id_fkey"
DETAIL:  Key (one_id)=(5) is not present in table "one".
                                  Table "tmp.one"
 Column |       Type        |                      Modifiers                       
--------+-------------------+------------------------------------------------------
 one_id | integer           | not null default nextval('one_one_id_seq'::regclass)
 name   | character varying | 
Indexes:
    "one_pkey" PRIMARY KEY, btree (one_id)

                             Table "tmp.two"
 Column |  Type   |                      Modifiers                       
--------+---------+------------------------------------------------------
 two_id | integer | not null default nextval('two_two_id_seq'::regclass)
 one_id | integer | 
Indexes:
    "two_pkey" PRIMARY KEY, btree (two_id)

該錯誤消息與實際插入或更新相同。 您會看到,引擎在與第一行發生沖突時反響了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM