I am building an application where users can sign up and then challenge each other (any other). When user 1 has challenged user 2, the score that exists between them is updated and stored (default score is 1 towards each other user). Mutually, user 2 can challenge user 1 and this updates another score.
The simplest way to represent this information is a n*n matrix (with a blank diagonal bcs you don’t have a “score” against yourself). My question is : how do you store it using MySQL ? I was thinking of a table with 3 columns : challenger, challenged, score, but that would result in a n² size and such an exponential factor seems inappropriate for such a simple request. Is there another, intended way to handle matrixes with MySQL ?
Thanks
Your initial idea seems right.
BTW n² is quadratic, not exponential.
MySQL should deal just fine with this.
Note that you only create a row when an actual challenge has taken place and a score needs to be recorded. So you will have exactly one row per challenge. If the same players can challenge each other more then once you should remove the unique key p1p2.
Usage examples
Now if you want to know how many points a player has scored you do
If you want to know all the players a player has challenged you do
If you do a small trick and add the following trigger, you can force that
player1.id < player2.id
Now you can simplify your query to see the cumulative score between two players.
Use the following query to select all players a player has battled with the scores
Hopes this gives you an idea of what is possible.