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

GROUP BY を使用せずに SUM を実行しようとしています。うまくいくかどうかはGROUP BY users.user_idわかりませんが、クエリの末尾に a を追加してみて、それが役立つかどうかを確認してください。

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 に答える