2013-02-06 35 views
0

我有兩個表,我試圖檢索(我知道)的具體信息。第一個表seasons是半靜態數據存儲,第二個表users_cards用於存儲用戶選擇。Mysql內部加入根據條件

我希望獲得的結果將貫穿每個賽季,爲每個賽季的賽季1-3和11分配一個「card_total」= 10。結果看起來類似於:

SEASON_ID | TOTAL | 
------------ ------------ 
1   | 123 
2   | 234 
3   | 345 
4   | 456 

縮寫&相關列/樣本數據如下:

# `seasons`: 

ID | ACTIVE | COMPLETE | 
---- ----------- --------------- 
1 | 0  | 1 
2 | 0  | 1 
3 | 0  | 1 
4 | 1  | 0 
5 | 0  | 0 

# `users_cards` 
# DESC: this table can store up to 10 choices per user for seasons 1-3 
#  and up to 11 choices for every season thereafter. 

USER_ID  | SEASON_ID | 
------------ --------------- 
1   | 1 
1   | 1 
2   | 1 
2   | 1 
1   | 2 
1   | 2 
1   | 2 

我已經與該查詢的一些變化玩耍了,但似乎沒有任何做的伎倆。這個查詢返回每個季節的總數,但它不是基於上面提到的「card_total」。

SELECT 
    c.season_id AS season_id, 
    c.card_total AS card_total, 
    c.total AS total 
FROM seasons s 
INNER JOIN (
    SELECT 
     uc.season_id, 
     COUNT(DISTINCT(user_id)) AS total, 
     CASE WHEN 
       uc.season_id = 1 
       OR uc.season_id = 2 
       OR uc.season_id = 3 
      THEN 10 
      ELSE 11 
     END AS card_total 
    FROM users_cards uc 
    GROUP BY uc.season_id 
) AS c ON c.season_id = s.id 
WHERE s.is_active = 1 
    OR s.is_complete = 1 
+0

但是季節3,4在表'users_cards'中沒有條目,爲什麼它在結果集中有總數? –

+0

對不起,我爲了不添加大量測試數據而縮寫。第3季和第4季目前確實有數據,並且看起來與上述樣本類似。第3季每個用戶最多包含10條記錄,第4季最多包含11條記錄。 –

回答

0

SUM()放在您的CASE...END附近。