here’s my first! quick rundown:
SCENARIO
i’m creating an app in which you can challenge another user to do something (e.g. run 4 miles this week, squat 3 plates, etc.). i’m more of a front end guy so i’ve had some issues with some of the DB trolling and what not.
for the friendship relationship of users i am using two rows to show reciprocation. i request you as a friend and my uid and your uid would be put into the relationships table. once you accept it, the reverse would be added.
when it comes to challenges, though, i’d really rather use only one row per challenge and then just update the TYPE as things progress. type 0 = challenge issued, 1 = challenge accepted, 2 = challenge complete.
i have another table with the info of each challenge (terms, begin date, end date, reward, etc.), so each challenge will be associated with a row in the challenge_info table—one more reason why i would like/need to only have one row per challenge in the challenge table.
PROBLEM
now the problem i’ve had is in trying to get a feed of a user’s most recent challenges. so, ou go to Tom’s profile page and you should see a list of his recent activity: “Tom challenged Amy and won! Tom lost to John. etc..”
I can left join the user table on the challenges table and get the challenges of a particular user, only certain types of challenges, and all that sorta thing, but i can’t find an efficient way to get the username of the person who challenged this user or who was challenged by this user.
TABLES
__USER__
ID UNAME
1 Tom
2 John
3 Timmy
__CHALLENGES__
CID Challenger_ID Challenged_ID Type
1 1 2 0
2 1 3 1
3 2 1 2
CLIFFS
What is the most efficient way to define this type of relationship and how can I join these tables such that I can find all the challenges Tom was a part of but also get the names and relationships (challenger or challenged) of the people he has interacted with?
Thanks for your time and consideration!
As long as Challenger_ID is indexed you would have no problem using 2 left joins (I assume USER.ID is indexed as a PK):
or just use inner join:
the execution plan will vary depending on your indexes but you get the idea.