2012-04-13 55 views
0

我有一個有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?

+0

@ user1330742好吧,我不知道你需要特權來編輯你自己的問題。 – 2012-04-13 07:07:58

回答

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; 
+0

謝謝,它完美地修復了它。這是我第一次在MySQL Statement中進行SUM實驗。感謝您也解釋我錯過了什麼。 – Teeoney 2012-04-13 07:10:08

+0

很高興幫助。在你碰到它的前幾次時,聚合總是讓人困惑,而且我之前肯定被這個bug咬了。 – Femi 2012-04-13 07:15:33

+0

最後一個問題。如果用戶沒有在數據庫中積累任何積分,則他們沒有顯示出來。 – Teeoney 2012-04-13 22:17:07