views:

29

answers:

2

I am developing an app that needs to match people together. Each person can only match with one other person.. So, in the table below I am trying to make it so that values from user1 & user2 are unique across both fields:

CREATE TABLE `match_table` (
    `user1` int(11) NOT NULL,
    `user2` int(11) NOT NULL,
UNIQUE KEY `user2` (`user2`),
UNIQUE KEY `user1` (`user1`))

So for example the following INSERT statement should ignore rows 2 and 4. Or at a minimum I need to be able to flag those rows to be ignored. Note that line 5 is OK because of the fact that line 2 and 4 have been ignored.

INSERT IGNORE INTO match_table (user1, user2)
VALUES
    (1,2),
    (2,3),
    (4,5),
    (6,4),
    (3,6)

Is there any index that can accomplish this? .. Otherwise is there some UPDATE I could do after insertion that could flag the ones I want to ignore?

+3  A: 

Assuming that the matching has no direction, you can use your existing table design but store the match both ways in the table:

INSERT IGNORE INTO match_table (user1, user2)
VALUES
(1,2),
(2,1),
(2,3),
(3,2),
(4,5),
(5,4),
(6,4),
(4,6),
(3,6),
(6,3)

If you just fetch all rows you will got each matching twice. You can avoid this as follows:

SELECT * FROM match_table WHERE user1 < user2
1, 2
3, 6
4, 5

One potential issue with this design is that it is possible to insert a row with a user who matches himself.

Mark Byers
Mark.. Thank you.. You are a genius. The answer is quite simple!!
Jesse
I would up vote you but i only have 1 reputation :(
Jesse
@Jesse: I and someone else upvoted your question so you have 11 rep now. You need just one more upvote... :)
Mark Byers
Thanks... this site is incredibly easy to get started with, it seems. BTW, I won't be inserting any row with a user that matches himself, no worries there.. and as this is just a temporary table the user1 < user2 trick will work fine. thanks again. I was struggling with super complex UPDATES that were just not working. lol.
Jesse
@Mark: I just realized I now have to figure out how to do an insert "both ways". As I am selecting this data from another table I don't see an obvious way to insert two rows for every one row.. with the second row having the values reversed.
Jesse
Well, I figured it out I can select the data twice and then do a UNION and then ORDER BY a 3rd primary id column
Jesse
A: 

If you are just asking for a database constraint, you can get that with UNIQUE INDEX ('user1','user2')

ThatSteveGuy