MySQL - WHERE子句+ JOIN

时间:2014-07-13 15:49:53

标签: mysql sql subquery

我有以下MySQL查询:

SELECT user_id, score, time 
FROM tests_1 T
WHERE T.score = (
SELECT MAX(T2.score)
FROM tests_1 T2
WHERE T2.user_id = T.user_id
)
ORDER BY score DESC, time ASC;

如何在'users'表中添加'users'列在users.user_id = tests_1.user_id?

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT T.user_id, U.username, T.score, T.time 
FROM tests_1 T
JOIN users U on U.user_id = T.user_id
WHERE T.score = (
SELECT MAX(T2.score)
FROM tests_1 T2
WHERE T2.user_id = T.user_id
)
ORDER BY T.score DESC, T.time ASC;

答案 1 :(得分:0)

加入吧。

SELECT T.user_id, T.score, T.time, u.username
FROM tests_1 T
JOIN users u ON u.user_id = T.user_id
WHERE T.score = (
SELECT MAX(T2.score)
FROM tests_1 T2
WHERE T2.user_id = T.user_id
)
ORDER BY T.score DESC, T.time ASC;

答案 2 :(得分:0)

SELECT user_id, score, time, U.username
FROM tests_1 T JOIN users U
    ON T.user_id = U.user_id
WHERE T.score = (
    SELECT MAX(T2.score)
    FROM tests_1 T2
    WHERE T2.user_id = T.user_id
)
ORDER BY score DESC, time ASC;