来自2个表的SELECT查询

时间:2015-02-05 10:57:51

标签: mysql sql

我有一张表matches,我希望从中获得得分最高的用户:

SELECT userId,SUM(score) AS score FROM `matches` GROUP BY userId ORDER BY score DESC

此输出2列userIdscore。好。 现在我有一个users表,我希望得到userId的更详细的输出。例如,我希望:userId-firstName-lastName-phone-address-score。这有可能通过简单的SQL查询吗? 谢谢。

3 个答案:

答案 0 :(得分:3)

您可以JOIN这样的表:

SELECT 
    matches.userId,
    SUM(matches.score) AS score,
    users.firstName,
    users.lastName,
    users.phone,
    users.address
FROM 
    `matches`
    JOIN users
        ON `matches`.userId=users.userId
GROUP BY 
    matches.userId,
    users.firstName,
    users.lastName,
    users.phone,
    users.address 
ORDER BY 
    score DESC

参考:

答案 1 :(得分:2)

SELECT userId, firstName, lastName, phone, address, SUM(score) AS score FROM matches join users on matches.user_id = users.user_id GROUP BY userId ORDER BY score DESC

答案 2 :(得分:2)

是的,只需使用JOIN语句,例如:

SELECT m.userId, SUM(m.score) AS score, u.firstName, u.lastName FROM `matches` AS m
INNER JOIN `users` AS u ON u.userId = m.userId
GROUP BY userId ORDER BY score DESC