我有這個多對多表,將人員表連接到自身:
CREATE TABLE IF NOT EXISTS friendship(
person_id INTEGER NOT NULL,
friend_id INTEGER NOT NULL,
date_friendship DATE NOT NULL DEFAULT CURRENT_DATE,
PRIMARY KEY(person_id, friend_id),
FOREIGN KEY(person_id) REFERENCES person(id),
FOREIGN KEY(friend_id) REFERENCES person(id),
UNIQUE(friend_id, person_id)
);
INSERT INTO friendship (person_id, friend_id)
VALUES (1, 2),
(1, 3),
(2, 3),
(4, 2);
應該禁止插入像 (person_id, friend_id) (2, 1) 這樣的行。因為我們已經插入了 (1, 2)。我的意思是,如果 1 是 2 的朋友,那么 2 也是 1 的朋友。
我不能強制執行這樣的約束。我試過UNIQUE(friend_id, person_id)了,但我仍然可以插入:
INSERT INTO friendship (person_id, friend_id)
VALUES (2, 1);
我應該如何處理這種情況?我應該使用不同型別的資料庫嗎?
uj5u.com熱心網友回復:
您可以在兩個值的“規范化”組合上創建唯一索引:
create unique index
on friendship (least(person_id,friend_id), greatest(person_id, friend_id) );
然后您可以unique(friend_id, person_id)從表定義中洗掉。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/535282.html
上一篇:帶計數聚合的SQL查詢
