多个联接基于两个不同的排序标准求和值

时间:2012-04-13 06:51:25

标签: php mysql

我有一个有4个表的数据库。

Table 1 - "company" table with company_id as the key
Table 2 - "users" table with the user_id as the key
Table 3 - "teams" table that references the company_id and the user_id (So that user can belong to multiple teams.
Table 4 - "points" table that references the company_id, the user_id, points_earned (Numeric value of points given), exchange_dte (0 - if the user has not used the points, otherwise a unixtime value)

鉴于已知的company_id,我试图呼叫属于该“团队”的所有用户,并显示他们的总积分和未交换的积分。以下MySQL只会为公司的#1团队提供第一个用户。目前数据库中有5个用户都获得了一些积分,有些是交换过的,有些则不是。

SELECT 
users.user_id AS u_id, 
SUM(points.points_earned) AS ttl_points,
SUM(case when exchange_dte = '0' then points.points_earned else 0 end) AS unused_points
FROM users
INNER JOIN teams ON teams.user_id = users.user_id
INNER JOIN points ON points.user_id = users.user_id
WHERE (teams.company_id = '1' AND points.company_id = '1' AND users.user_active = '1');

然后我尝试将user_id添加到Sum调用中。并最终得到同样的东西。

SELECT
users.user_id AS u_id, 
SUM(case when points.user_id = users.user_id then points.points_earned else 0 end) AS ttl_points,
SUM(case when points.exchange_dte = '0' AND points.user_id = users.user_id then points.points_earned else 0 end) AS unused_points
FROM users
INNER JOIN teams ON teams.user_id = users.user_id
INNER JOIN points ON points.user_id = users.user_id
WHERE (teams.company_id = '1' AND points.company_id = '1' AND users.user_active = '1')
ORDER BY ttl_points;

有趣的是,第一个用户的总分看起来是数据库中的所有点,即使他们有一个user_id和与他们相关联的company_id

思想?

1 个答案:

答案 0 :(得分:0)

您尝试在不使用GROUP BY的情况下执行SUM:不确定它是否适合您,但尝试在查询结束后添加GROUP BY users.user_id并查看是否可以帮助您。

SELECT
users.user_id AS u_id, 
SUM(case when points.user_id = users.user_id then points.points_earned else 0 end) AS ttl_points,
SUM(case when points.exchange_dte = '0' AND points.user_id = users.user_id then points.points_earned else 0 end) AS unused_points
FROM users
INNER JOIN teams ON teams.user_id = users.user_id
INNER JOIN points ON points.user_id = users.user_id
WHERE (teams.company_id = '1' AND points.company_id = '1' AND users.user_active = '1') GROUP BY users.user_id
ORDER BY ttl_points;