[英]Mysql Inner Join based on condition
I have two tables that I'm attempting to retrieve specific information from (duh I know). 我有两个试图从中检索特定信息的表(我知道)。 The first table seasons
is semi-static data storage and the second table users_cards
is used to store user choices. 第一个表seasons
是半静态数据存储,而第二个表users_cards
用于存储用户选择。
The result I am hoping to achieve would go through each season, assign a "card_total" = 10 for seasons 1-3 and 11 for each season moving forward. 我希望获得的结果将贯穿每个赛季,为第1-3赛季分配“ card_total” = 10,并为每个向前的赛季分配11。 The result would look something similar to: 结果看起来类似于:
SEASON_ID | TOTAL |
------------ ------------
1 | 123
2 | 234
3 | 345
4 | 456
The abbreviated & pertinent columns / sample data is as follows: 缩写和相关的列/样本数据如下:
# `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
I've played around with a few variations of this query but nothing seems to be doing the trick. 我已经处理了该查询的一些变体,但似乎没有办法解决问题。 This query returns the total count for each season but it's not based off of the "card_total" I mentioned above. 该查询返回每个季节的总数,但是它不是基于我上面提到的“ 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.