2010-05-11 136 views
0

我有兩個表:一般多對一對多的關係問題(PostgreSQL系統)

CREATE TABLE "public"."auctions" (
"id" VARCHAR(255) NOT NULL, 
"auction_value_key" VARCHAR(255) NOT NULL, 
"ctime" TIMESTAMP WITHOUT TIME ZONE NOT NULL, 
"mtime" TIMESTAMP WITHOUT TIME ZONE NOT NULL, 
CONSTRAINT "pk_XXXX2" PRIMARY KEY("id"), 
); 

CREATE TABLE "public"."auction_values" (
"id" NUMERIC DEFAULT nextval('default_seq'::regclass) NOT NULL, 
"fk_auction_value_key" VARCHAR(255) NOT NULL, 
"key" VARCHAR(255) NOT NULL, 
"value" TEXT, 
"ctime" TIMESTAMP WITHOUT TIME ZONE NOT NULL, 
"mtime" TIMESTAMP WITHOUT TIME ZONE NOT NULL, 
CONSTRAINT "pk_XXXX1" PRIMARY KEY("id"), 
); 

如果我想創建像auction_value_key一個多一對多的關係這樣的:

ALTER TABLE "public"."auction_values" 
    ADD CONSTRAINT "auction_values_fk" FOREIGN KEY ("fk_auction_value_key") 
    REFERENCES "public"."auctions"("auction_value_key") 
    ON DELETE NO ACTION 
    ON UPDATE NO ACTION 
    NOT DEFERRABLE; 

我得到這個SQL錯誤:

ERROR: there is no unique constraint matching given keys for referenced table "auctions" 

問:

正如你可能會看到,我想「auction_values」將被「重用」,由不同的拍賣,而無需複製他們每次競價...所以我不想在一個關鍵關係拍賣表中的「id」字段...

我在這裏想錯了什麼,或者是什麼交易? ;)

感謝

回答

1

一對多的關係。它將包含拍賣和auction_values之間的映射。它需要兩列:auction_id和auction_value_id。

+0

這是典型的做法規範化,布拉沃 – stjohnroe 2010-05-11 10:45:14

+0

或許沒錯,但不一定:)也許'auction_value_key'組行的集合來自'auction_values'?在這種情況下,提出的模式是不正確的。 – Unreason 2010-05-11 13:25:19

0

如果你想auction_values由不同的拍賣被重用,你應該聲明的約束反過來:你需要額外的表到多對一模型

ALTER TABLE auctions 
ADD CONSTRAINT fk_auction_values 
FOREIGN KEY (auction_value_key) 
REFERENCES auction_values (id) 
0

引述wikipedia

In the context of relational databases, a foreign key is a referential constraint between two tables. 1 The foreign key identifies a column or a set of columns in one (referencing) table that refers to set of columns in another (referenced) table. The columns in the referencing table must be the primary key or other candidate key in the referenced table. The values in one row of the referencing columns must occur in a single row in the referenced table. Thus, a row in the referencing table cannot contain values that don't exist in the referenced table (except potentially NULL). This way references can be made to link information together and it is an essential part of database normalization. Multiple rows in the referencing table may refer to the same row in the referenced table. Most of the time, it reflects the one (master table, or referenced table) to many (child table, or referencing table) relationship.

由於Quassnoi所指出的,它的聲音,如果你想在auction_valuesauctions參考單行多行。

爲此,主表或引用表爲auction_values,子表或引用表爲auction_values。

如果另一方面亞歷克斯是正確的,並且您想引用auction_values中的多行,您將需要另一個表。

該表格將幫助您將多對多關係(無法在物理數據庫級別直接實現)轉換爲兩個一對多關係。

通常,您可以從兩張起始表中存儲此表,並以這種方式您可以關聯auction_valuesauctions的任何記錄組合。

然而,這可能是過於籠統,你實際上可能是一個表後auction_value_keys (auction_value_key)