0

我有一个有 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 与他们相关联

想法?

4

1 回答 1

0

You're trying to do a SUM without using GROUP BY: not sure if it will work for you but try this adding a GROUP BY users.user_id after the end of the query and see if that helps you out.

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;
于 2012-04-13T07:07:00.290 回答