I have several tables I need help to generate a query string. I am currently querying each of the tables and combining the results in the frontend which is making too many requests to the backend
Below is the structure of my tables (See this Sample sqlfiddle )
users
| id | first_name | last_name |
|---|---|---|
| 1 | John | Doe |
| 2 | Peter | Parker |
events
| id | name |
|---|---|
| 1 | New Year wake contest |
| 2 | Bright Monday contest |
question
| id | description | points |
|---|---|---|
| 1 | Some Question Here | 2 |
| 2 | Another Question Here | 4.5 |
A question can belong to many events while events can have many questions
event_question
| question_id | event_id |
|---|---|
| 1 | 2 |
| 1 | 1 |
Answers belong to a question
answers
| id | description | question_id | is_correct |
|---|---|---|---|
| 1 | Answer is 4 | 1 | 1 |
| 2 | Not True | 1 | 0 |
The final step is to save the info about an exam attempt
attempts
| user_id | attempt | question_id | answer_id | event_id |
|---|---|---|---|---|
| 2 | 1 | 1 | 1 | 2 |
| 2 | 1 | 2 | 8 | 2 |
I need help with coming up with a query that will retrieve the rank of a specific contest.
Lets say event_id = 1
Expected output
For event with id = 1 the rank will be
| user_id | first_name | last_name | points |
|---|---|---|---|
| 5 | Paul | Morphy | 13.5 |
| 4 | Bobby | Fisher | 9.5 |
| 1 | John | Doe | 9.5 |
| 2 | Peter | Parker | 6 |
| 3 | Alexander | Alekhine | 6 |
For event with id = 2 the rank will be
| user_id | first_name | last_name | points |
|---|---|---|---|
| 4 | Bobby | Fisher | 7 |
| 1 | John | Doe | 6 |
| 2 | Peter | Parker | 6 |
| 5 | Paul | Morphy | 5 |
| 3 | Alexander | Alekhine | 3 |
points is the sum of points for the questions that a given user provided correctly
I am using PHP (Laravel) and MySql. A solution with Laravel eloquent or simply an SQL query are both welcomed