MySQL从三个表中选择

时间:2014-08-21 14:15:29

标签: mysql sql

我需要写入查询获取哪些国家/地区有专业的最高汇款单。主表是:used_money

我有3个表:used_moneyusersgroups

我无法发布图片,请点击此处:

enter image description here

我需要得到这样的结果:

Luxembourg    Hacker 200
Albania       Hacker 120
United States Boss    55

1 个答案:

答案 0 :(得分:0)

这样的事情?

QUERY:

SELECT country, profession, MAX(money) AS money 
FROM
(   SELECT u.country, g.profession, SUM(um.money) AS money
    FROM user_money um
    JOIN users u ON u.id = um.user_id
    JOIN groups g ON g.id = um.group_id
    GROUP BY g.profession, u.country
    ORDER BY um.money DESC
) t
GROUP BY country
ORDER BY money DESC

SEE DEMO

输出:

+---------------+------------+-------+
| country       | profession | money |
+---------------+------------+-------+
| Luxembourg    | Hacker     |  200  |
| Albania       | Hacker     |  120  |
| United States | Boss       |  55   |
+---------------+------------+-------+