1

对于在线学习网站,教师可以创建他们想教授的任何课程。每门课程都有课程。然后,学生可以订阅这些课程或教师添加的任何未来课程,如果他们愿意的话。学生可以通过以下三种方式订阅老师的课程:

1. 仅订阅所有课程(老师当前和未来的所有课程)例如。subscriber_id 12
2. 订阅所有课程,然后取消订阅个别课程(即使取消订阅所有
    当前的个别课程,他们仍将订阅未来的课程)例如。subscriber_id 10 3.仅
订阅个别课程,例如。订阅者 ID 11

subscribed_courses 表如下所示:

subscribed_courses (Table with all member chosen resort services)
teacher_id  subscriber_id  course_id    sub_type
    4            10            0          all
    4            10            1         unsub
    4            10            2         unsub
    4            11            4          sub
    4            12            0          all

当老师添加新课程或课程时,我们需要扫描 subscribed_courses 表,并查看哪些订阅的学生应该收到电子邮件。问题是让以下查询工作以将正确的订阅者 ID 发送到电子邮件。对于这个特定的查询示例,让我们使用 course_id 2,它刚刚添加了一个新课程,我们需要向所有订阅者发送电子邮件。必须有更好的方法来实现这一点:

SELECT DISTINCT subscriber_id 
FROM subscribed_courses
WHERE teacher_id='4'
//AND #1 (sub_type='sub' AND course_id='2') //individually subscribed
      #2 ((sub_type='all' AND course_id='0') AND (sub_type='unsub' AND course_id<>'2')) //subscribed to all, ensure subscriber didn't unsub from this course [all subscribed 1 row + more row(s) for unsub]
      #3 (sub_type='all' AND course_id='0') //all subscribed [if this is one row only for subscriber]

知道如何在我们的情况下获得正确的订阅者 ID 或更好的工作解决方案吗?

4

2 回答 2

1

更新尝试更简洁的版本

SELECT subscriber_id
  FROM subscribed_courses
 WHERE teacher_id = 4
   AND course_id IN(0, 2)
 GROUP BY teacher_id, subscriber_id
HAVING SUM(       
       CASE WHEN sub_type = 'all'   THEN 1  ELSE 0  END 
     + CASE WHEN sub_type = 'sub'   THEN 1  ELSE 0  END 
     + CASE WHEN sub_type = 'unsub' THEN -2 ELSE 0  END) > 0

输出:

| SUBSCRIBER_ID |
-----------------
|            12 |

这是SQLFiddle演示

于 2013-06-07T03:44:00.910 回答
0

请检查这是否是您需要的。谢谢。

SELECT DISTINCT subscriber_id 
FROM subscribed_courses
WHERE teacher_id='4'
AND ((sub_type='sub' AND course_id='2')
union 
SELECT DISTINCT subscriber_id 
FROM subscribed_courses
WHERE teacher_id='4'
AND ((sub_type='all' AND course_id='0') AND (sub_type='unsub' AND course_id<>'2')) 
union
SELECT DISTINCT subscriber_id 
FROM subscribed_courses
WHERE teacher_id='4'
AND (sub_type='all' AND course_id='0'))
于 2013-06-07T03:12:05.637 回答