[英]Group by on first table and keep the highest value of the second table
這是我的桌子
+----------+-----------+
| id | user_id |
+----------+-----------+
| 1 | 1 |
+----------+-----------+
| 2 | 1 |
+----------+-----------+
| 3 | 1 |
+----------+-----------+
| 4 | 2 |
+----------+-----------+
| 5 | 2 |
+----------+-----------+
| 6 | 2 |
+----------+-----------+
| 7 | 3 |
+----------+-----------+
| 8 | 3 |
+----------+-----------+
| 9 | 3 |
+----------+-----------+
我的第二張桌子
+----------+---------+
| id | score |
+----------+---------+
| 1 | 10 |
+----------+---------+
| 2 | 20 |
+----------+---------+
| 3 | 5 |
+----------+---------+
| 4 | 40 |
+----------+---------+
| 5 | 15 |
+----------+---------+
| 6 | 10 |
+----------+---------+
| 7 | 5 |
+----------+---------+
| 8 | 30 |
+----------+---------+
| 9 | 10 |
+----------+---------+
我需要從這些表中選擇用戶獲得的最高分數。
這是我的MySql查詢
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
我的願望結果是
+----------+-----------+---------+
| id | user_id | score |
+----------+-----------+---------+
| 4 | 2 | 40 |
+----------+-----------+---------+
| 8 | 3 | 30 |
+----------+-----------+---------+
| 2 | 1 | 20 |
+----------+-----------+---------+
但是我得到的是
+----------+-----------+---------+
| id | user_id | score |
+----------+-----------+---------+
| 4 | 2 | 40 |
+----------+-----------+---------+
| 1 | 1 | 10 |
+----------+-----------+---------+
| 7 | 3 | 5 |
+----------+-----------+---------+
當我使用GROUP BY
子句時,MySql總是從table_1中選擇最低的id
。
我嘗試像這樣使用MAX
命令
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
結果我得到了
+----------+-----------+---------+-----------+
| id | user_id | score | max_score |
+----------+-----------+---------+-----------+
| 4 | 2 | 40 | 40 |
+----------+-----------+---------+-----------+
| 1 | 1 | 10 | 20 |
+----------+-----------+---------+-----------+
| 7 | 3 | 5 | 30 |
+----------+-----------+---------+-----------+
我相信我希望很容易得到結果,但是我無處可去。
更新1
這個問題被標記為重復,但是很遺憾,在給定的頁面上我找不到任何解決方案。
這是我正在嘗試的查詢,但失敗。
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
它給我錯誤Unknown column t1.user_id
我正在嘗試從table_2
的列score
獲取最高的值,並將結果按table_1
user_id
分組。
這些頁面上給出的示例僅針對一個表,我無法在我的場景中進行。
編寫一個子查詢,以獲取每個user_id
的最高分數。 然后將其與您的表一起獲得具有最高得分的行。
SELECT t1.id, t1.user_id, max_score
FROM table_1 AS t1
JOIN table_2 AS t2 ON t1.id = t2.id
JOIN (
SELECT t1.user_id, MAX(t2.score) AS max_score
FROM table_1 AS t1
JOIN table_2 AS t2 on t1.id = t2.id
GROUP BY t1.user_id) AS t_max
ON t1.user_id = t_max.user_id AND t2.score = t_max.max_score
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.