我能夠在Oracle中執行以下操作。注意最後一次插入失敗的原因,我相信這就是你以後的樣子。
CREATE TABLE product (
id INTEGER NOT NULL,
category_id INTEGER NOT NULL,
PRIMARY KEY (id),
CONSTRAINT uq_prod_cat UNIQUE (id,category_id)
);
INSERT INTO product (
id,
category_id
) VALUES (
1,
1
);
CREATE TABLE tags (
id INTEGER NOT NULL,
category_id INTEGER NOT NULL,
PRIMARY KEY (id),
CONSTRAINT uq_tag_cat UNIQUE (id,category_id)
);
INSERT INTO tags (
id,
category_id
) VALUES (
1,
1
);
INSERT INTO tags (
id,
category_id
) VALUES (
2,
1
);
INSERT INTO tags (
id,
category_id
) VALUES (
3,
2
);
CREATE TABLE product_tags (
id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
category_id INTEGER NOT NULL,
tag_id INTEGER NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (product_id,category_id)
REFERENCES product (id,category_id),
FOREIGN KEY (tag_id,category_id)
REFERENCES tags (id,category_id)
);
INSERT INTO product_tags (
id,
product_id,
category_id,
tag_id
) VALUES (
1,
1,
1,
1
);
1 row inserted.
INSERT INTO product_tags (
id,
product_id,
category_id,
tag_id
) VALUES (
2,
1,
1,
2
);
1 row inserted.
INSERT INTO product_tags (
id,
product_id,
category_id,
tag_id
) VALUES (
3,
1,
1,
3
);
Error starting at line : 35 in command -
INSERT INTO product_tags (id, product_id, category_id, tag_id) VALUES (3, 1, 1, 3)
Error report -
ORA-02291: integrity constraint (SYS_C008023) violated - parent key not found
爲什麼不只是把你的產品次要鑰匙?因此,雙SIM卡的產品ID爲X並且必須與類別ID Y等一起使用?那麼您不能重複使用不同類別的產品 - 但它可以解決您的需求。 – ssn
對不起,我沒有明白。您是否建議在產品表中添加新的字段? – kYuZz
是的。因此,您的產品/標籤屬於特定類別 - 當您將新產品/標籤添加到類別中時,該類別將保持不變 – ssn