繁体   English   中英

MySQL条件内联接

[英]Mysql Inner Join based on condition

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

我希望获得的结果将贯穿每个赛季,为第1-3赛季分配“ card_total” = 10,并为每个向前的赛季分配11。 结果看起来类似于:

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

SUM()放在您的CASE...END周围。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM