MySQL Join plus Count plus Sum

时间:2012-06-27 21:45:24

标签: php mysql join

这是一个复杂的查询,我希望能够实现一个语句,而不是在PHP中处理数组值。

达到所需的输出:

User    Jobs    Total
John D. 5       $1245.67
Mary L. 3       $800.56

到目前为止,这是我的查询:

SELECT
  SUM(job.cost) AS sum,
  COUNT(DISTINCT job.user) as count,
  user.id, user.firstname, user.lastname
FROM      `job`
LEFT JOIN `user` ON job.user = user.id
GROUP BY user.id

但计数值是错误的:它是不同的用户,所以当然每个都是错的。我该如何解决这个问题?

user

id, name, etc.

job

id, user, cost

一个user到多个job


更新

这似乎正常:

SELECT 
  SUM(job.cost) AS sum,
  COUNT(1) as count,
  user.id, user.firstname, user.lastname
FROM `job`
LEFT JOIN `user` ON job.user = user.id
GROUP BY user.id

1 个答案:

答案 0 :(得分:2)

SET @seq = 0;

SELECT place FROM

(SELECT
  @seq := @seq + 1 AS place
  SUM(job.cost) AS sum,
  COUNT(1) as count,
  user.id, user.firstname, user.lastname
FROM      `job`
LEFT JOIN `user` ON job.user = user.id
GROUP BY user.id
ORDER BY COUNT(1) DESC) 

AS list
WHERE list.id = 'my_user_id'