【问题标题】:What will be the query for the following query?以下查询的查询是什么?
【发布时间】:2020-09-25 13:43:31
【问题描述】:
SELECT s.subject_id
     , s.subject_name
     , t.class_id
     , t.section_id
     , c.teacher_id
  FROM school_timetable_content c
  JOIN s  
    ON c.subject_id = s.subject_id
  JOIN school_timetables t 
    ON t.timetable_id = c.timetable_id
 WHERE c.teacher_id = 184
   AND t.class_id = 24
   AND t.school_id = 28

从上面的查询中,我得到如下结果:-

再次根据上述结果,我想获得与所有唯一 section_id 15、16,26 相关联的 subjects。即预期输出 Hindi,Maths

【问题讨论】:

标签: mysql sql database qsqlquery mysql-select-db


【解决方案1】:

我们的想法是过滤这三个部分。如果三个都存在,则聚合并计数:

SELECT s.subject_id, s.subject_name
FROM school_timetable_content tc JOIN
     school_subjects s
     ON tc.subject_id = s.subject_id JOIN
     school_timetables t
     ON t.timetable_id = tc.timetable_id
WHERE tc.teacher_id = 184 AND 
      t.class_id = 24 AND
      t.school_id = 28 AND
      t.section_id IN (15, 16, 26)
GROUP BY s.subject_id, s.subject_name
HAVING COUNT(*) = 3;

这假定section_id 没有重复。如果可能,请改用HAVING(COUNT(DISTINCT section_id)) = 3

请注意,表别名的使用使查询更易于编写和阅读。

【讨论】:

    猜你喜欢
    • 2014-04-19
    • 2020-04-14
    • 2021-07-16
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多