我有users
表和3个用户收入表
我要做的是根据这3张表选择收入最高的前10位用户
我从昨天起就一直在努力解决这个问题,我无法让它发挥作用
我想将这3个收入表总计为总数。
对此有任何帮助吗?
SELECT
users.first_name,
users.last_name,
(select SUM(`value`) from `earnings1` where users.id = earnings1.user) as earnings1,
(select SUM(`value`) from `earnings2` where users.id = earnings2.user) as earnings2,
(select SUM(`value`) from `earnings3` where users.id = earnings3.user) as earnings3,
(earnings1 + earnings2 + earnings3) as total
FROM users
GROUP BY users.id
ORDER BY total DESC
LIMIT 10
我现在得到的错误是:
未知栏目'收入1'在'字段列表'
答案 0 :(得分:1)
这应该适合你:
select first_name, last_name,
(earnings1 + earnings2 + earnings3) total from
(select users.id, users.first_name, users.last_name,
(select sum(`value`) from `earnings1` where users.id = earnings1.user) as earnings1,
(select sum(`value`) from `earnings2` where users.id = earnings2.user) as earnings2,
(select sum(`value`) from `earnings3` where users.id = earnings3.user) as earnings3
from users group by 1,2,3) t
order by 3 desc limit 10
t 是您从内部查询中为结果集提供的名称。它有点类似于公用表表达式但不精确。 MySQL要求您为此结果集命名。
1,2,3 您可以使用1,2,3或者您可以使用列名 users.id,users.first_name,users.last_name 作为您的分组列。 1,2,3表示select语句中的第一,第二和第三列。