I want to create a MySQL table to hold relationship data between users. The relationship between user A to B and user B to A can be different.
Example:
- Relationship of (from) Bob (to) Alice: 0.9 – Bob loves Alice’s stuff.
- Relationship of (from) Alice (to) Bob: 0.5 – Alice finds Bob’s stuff mediocre.
My question:
I have implemented two CONSTRAINTS as UNIQUE KEYs on two FOREIGN KEYS that reference user_ids in a users table. Can I do this? Are they treated as two separate UNIQUE KEYs?
How can I implement a CONSTRAINT that will only allow one occurrence of each (from) UserA (to) UserB relationship and (from) UserB (to) UserA relationship per user_id? Am I going about it the right way?
The SQL:
CREATE TABLE relationships (
relationship_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
from_user_id MEDIUMINT UNSIGNED NOT NULL,
to_user_id MEDIUMINT UNSIGNED NOT NULL,
relationship_level DECIMAL(1,1) NOT NULL,
PRIMARY KEY (relationship_id),
FOREIGN KEY (from_user_id) REFERENCES users (user_id)
ON DELETE CASCADE ON UPDATE NO ACTION,
FOREIGN KEY (to_user_id) REFERENCES users (user_id)
ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT from_to_relationship UNIQUE KEY (from_user_id, to_user_id),
CONSTRAINT to_from_relationship UNIQUE KEY (to_user_id, from_user_id),
INDEX relationship_from_to (relationship_id, from_user_id, to_user_id, relationship_level),
INDEX relationship_to_from (relationship_id, to_user_id, from_user_id, relationship_level)
) ENGINE=INNODB;
I hope someone can assist.
Keep only one of these
UNIQUEconstraints – there is no need to have both. When a row failsUNIQUE KEY (from_user_id, to_user_id)it also failsUNIQUE KEY (to_user_id, from_user_id)and vice versa, so they are logically equivalent. Even with only oneUNIQUEconstraint, when trying to represent a relationship between Alice and Bob, you can have at most one {Alice, Bob} row, and at most one {Bob, Alice} row.As for performance (i.e. traversing the relationship in both directions), you might want to consider indexing
{from_user_id, to_user_id}(for “forward” traversal) and/or{to_user_id, from_user_id}(for “backward” traversal). You might even ditch the surrogate primary key (relationship_id) and go for the natural PK, thus lowering the need for indexing (secondary indexes are expensive for clustered tables, see Understanding InnoDB clustered indexes, section “Disadvantages of clustering”).In my opinion, your table should look like this:
NOTE: Whether you include
relationship_levelin INDEX or not depends on whether you want index-only scan in “backward” direction as well. The “forward” direction is naturally covered by the PK (since InnoDB is clustered).