Mysql Inner Join基于条件

时间:2013-02-06 07:48:43

标签: mysql inner-join case-when

我有两个表,我试图从(我知道)中检索特定信息。第一个表seasons是半静态数据存储,第二个表users_cards用于存储用户选择。

我希望实现的结果将贯穿每个赛季,为每个赛季的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

1 个答案:

答案 0 :(得分:0)

SUM()放在CASE...END

附近