1

我有 2 张桌子:

current_challenges (challenge_id, award_type, award_at_count, expires_in_hours)

user_challenges (user_challenge_id, user_id, challenge_id, awarded)

current_challenges表格是挑战的类型,表格user_challenges当前是“活动的”并且已经“完成”了不同用户的挑战。这些表通过challenge_id. 一个已完成的挑战是一个带有awarded!= '0000-00-00 00:00:00' 的挑战,而 'active'awarded是一个设置的日期时间。

我想做的是获取一个challenge_id尚未由该特定用户完成的随机单曲,但如果该用户已经有 2 个award_type该用户处于活动状态,则不应选择它。

因此,对于每个用户,最多只能有 2 个挑战“活动”且具有相同的奖励类型。

例子:

当前挑战表:

challenge_id    award_type  award_at_count  expires_in_hours
49  1   1   24
50  1   2   24
51  1   3   24
52  2   4   24
53  2   5   24
54  2   6   24

用户挑战表:

user_challenge_id   user_id     challenge_id    awarded
1   8   49  0000-00-00 00:00:00
2   8   50  0000-00-00 00:00:00
3   8   52  2012-12-06 13:58:27
4   11  53  0000-00-00 00:00:00
5   11  54  0000-00-00 00:00:00

对于用户 8,challenge_id不会选择 49,50,因为它们已经处于活动状态。51 不会,因为已经有 2 个活动的award_type= '1'。52 不会,因为它已经完成,留下 53 或 54 作为返回challenge_id

很抱歉,这篇文章很长,但希望尽可能清楚。过去一天我有一场戏,但无处可去……我猜在某个地方LEFT JOINHAVING COUNT()但我无法弄清楚……

4

1 回答 1

1

我认为这就是你想要的:

SELECT c.challenge_id
FROM current_challenges AS c
  LEFT JOIN
      ( SELECT cc.award_type                       --- find award types
        FROM current_challenges AS cc              --- with
          JOIN user_challenges AS ac            
            ON ac.challenge_id = cc.challenge_id   --- challenges
        WHERE ac.user_id = 8                       --- for this user
          AND ac.awarded = '0000-00-00'            --- that are active
        GROUP BY cc.award_type
        HAVING COUNT(*) >= 2                       --- and 2 or more
      ) AS ac
      ON ac.award_type = c.award_type
WHERE ac.award_type IS NULL                        --- and exclude them

  AND c.challenge_id NOT IN                        --- then exclude
      ( SELECT challenge_id                        --- any other challenges
        FROM user_challenges AS uc
        WHERE uc.user_id = 8                       --- for this user
      )
ORDER BY RAND()                                    --- order the result randomly
    LIMIT 1 ;                                      --- and choose one
于 2012-12-09T13:01:45.950 回答