Here are my tables
+----------+-----------+
| id | user_id |
+----------+-----------+
| 1 | 1 |
+----------+-----------+
| 2 | 1 |
+----------+-----------+
| 3 | 1 |
+----------+-----------+
| 4 | 2 |
+----------+-----------+
| 5 | 2 |
+----------+-----------+
| 6 | 2 |
+----------+-----------+
| 7 | 3 |
+----------+-----------+
| 8 | 3 |
+----------+-----------+
| 9 | 3 |
+----------+-----------+
My second table
+----------+---------+
| id | score |
+----------+---------+
| 1 | 10 |
+----------+---------+
| 2 | 20 |
+----------+---------+
| 3 | 5 |
+----------+---------+
| 4 | 40 |
+----------+---------+
| 5 | 15 |
+----------+---------+
| 6 | 10 |
+----------+---------+
| 7 | 5 |
+----------+---------+
| 8 | 30 |
+----------+---------+
| 9 | 10 |
+----------+---------+
I need to select the highest score achieved by a user from these tables.
Here is my MySql query
SELECT * FROM
table_1 AS t1
INNER JOIN
table_2 AS t2 ON
t1.id = t2.id
WHERE t2.score > 10
GROUP BY t1.user_id
ORDER BY t2.score DESC
My desire result is
+----------+-----------+---------+
| id | user_id | score |
+----------+-----------+---------+
| 4 | 2 | 40 |
+----------+-----------+---------+
| 8 | 3 | 30 |
+----------+-----------+---------+
| 2 | 1 | 20 |
+----------+-----------+---------+
But what I get is
+----------+-----------+---------+
| id | user_id | score |
+----------+-----------+---------+
| 4 | 2 | 40 |
+----------+-----------+---------+
| 1 | 1 | 10 |
+----------+-----------+---------+
| 7 | 3 | 5 |
+----------+-----------+---------+
MySql is always selecting the lowest id
from table_1 when I'm using the GROUP BY
clause
I tried using the MAX
command like this
SELECT *, MAX(t2.score) AS max_score FROM
table_1 AS t1
INNER JOIN
table_2 AS t2 ON
t1.id = t2.id
WHERE t2.score > 10
GROUP BY t1.user_id
ORDER BY t2.score DESC
LIMIT 10
And the result I'm getting
+----------+-----------+---------+-----------+
| id | user_id | score | max_score |
+----------+-----------+---------+-----------+
| 4 | 2 | 40 | 40 |
+----------+-----------+---------+-----------+
| 1 | 1 | 10 | 20 |
+----------+-----------+---------+-----------+
| 7 | 3 | 5 | 30 |
+----------+-----------+---------+-----------+
I believe the result I wish it quite easy to get but I'm nowhere there.
Update 1
This question was marked duplicate but unfortunately I couldn't find any solution on that given page.
Here is the query that I'm trying but it fails.
SELECT * AS max_score FROM
table_1 AS t1
INNER JOIN
(
SELECT *, MAX(score) AS max_score
FROM table_2
GROUP BY t1.user_id
) AS t2
ON
t1.id = t2.id
WHERE t2.score > 10
ORDER BY t2.score DESC
LIMIT 10
It gives me the error Unknown column t1.user_id
I'm trying to get the highest value from the column score
which is in table_2
and group the results by user_id
which is in table_1
.
The examples given on those pages target only one table and I'cant make that work on my scenario.