简体   繁体   中英

How does a MySQL composite unique key work with two foreign key fields referencing the same column?

Say I have the following tables (I don't really this is just for example):

CREATE TABLE PERSON(
  ID BIGINT NOT NULL AUTO_INCREMENT,
  PRIMARY KEY(ID)
);

CREATE TABLE FRIENDSHIP(
  ID BIGINT NOT NULL AUTO_INCREMENT,
  PERSON_ID_A BIGINT NOT NULL,
  PERSON_ID_B BIGINT NOT NULL,
  PRIMARY KEY(ID),
  FOREIGN KEY(PERSON_ID_A) REFERENCES PERSON(ID),
  FOREIGN KEY(PERSON_ID_B) REFERENCES PERSON(ID)
);

The person table represents people, and the friendship table represents friendships between people.

I would like to allow only one friendship record to exist between two unique people, so my initial reaction would be to add the following to the friendship table:

UNIQUE KEY(PERSON_ID_A, PERSON_ID_B)

However I suspect that this will still allow multiple friendships to form between two people if the following were to occur:

INSERT INTO FRIENDSHIP(PERSON_ID_A, PERSON_ID_B) VALUES (1, 2);
INSERT INTO FRIENDSHIP(PERSON_ID_A, PERSON_ID_B) VALUES (2, 1);

Does the single unique key above prevent this insert pair from successfully applying? If not, is it possible to prevent them using some special variation of a composite unique key, or will I need to process this in a trigger? If the single unique key DOES prevent the above inserts, how can I allow them?

you can create an index such that either combination will be allowed only once using least and greatest functions.

create unique index idx_PersonA_PersonB on 
FRIENDSHIP(least(PERSON_ID_A, PERSON_ID_B), greatest(PERSON_ID_A, PERSON_ID_B));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM