我有一個有4個表的數據庫。Muliple基於兩種不同的評論加入總值
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到總和調用。並以同樣的事情結束。
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?
@ user1330742好吧,我不知道你需要特權來編輯你自己的問題。 – 2012-04-13 07:07:58