0

我有一个团队、学校和作业的数据库。选择作业后,学校(无论如何都是其用户)可以将团队添加到作业中,以便他们可以开始处理作业。ER 图如下所示: 数据库的ER图 重要提示:即使数据库的设置另有说明,团队<-> 分配关系也是 1:N。一个团队只能完成一项任务。这是通过 ORM 系统控制的。

现在有一个问题:数据库中有团队在处理不属于他们学校的作业:学校选择作业,创建了一个团队并删除了他们的作业选择。我需要找到属于这种情况的学校(id、name)。

到目前为止,我设法提出的最佳查询是:

SELECT schools.school_id, schools.name
FROM schools
LEFT JOIN teams ON schools.school_id = teams.school_id
LEFT JOIN assignment_teams ON teams.team_id = assignment_teams.team_id
LEFT JOIN assignment_schools ON schools.school_id = assignment_schools.school_id
WHERE assignment_teams.assignment_id != assignment_schools.assignment_id;

但是当我手动检查结果时它不起作用。我正在寻找的正确查询是什么?

4

1 回答 1

1

其中一个应该可以工作,但我不知道哪个是最快的:

  1.   SELECT school_id
      FROM teams
      INNER JOIN assignment_teams ON teams.team_id = assignment_teams.team_id
      LEFT JOIN assignment_schools ON assignment_schools.school_id = teams.school_id AND  assignment_schools.assignment_id = assignment_teams.assignment_id
      WHERE assignment_schools.school_id IS NULL
    
  2. SELECT school_id
      FROM teams
      INNER JOIN assignment_teams ON teams.team_id = assignment_teams.team_id
      WHERE assignment_id NOT IN (
        SELECT assignment_id
          FROM assignment_schools
          WHERE assignment_schools.school_id = teams.school_id
      )
    
  3. SELECT school_id
      FROM teams
      INNER JOIN assignment_teams ON teams.team_id = assignment_teams.team_id
      WHERE NOT EXISTS (
        SELECT *
          FROM assignment_schools
          WHERE assignment_schools.school_id = teams.school_id
          AND assignment_schools.assignment_id = assignment_teams.assignment_id
      )
    
于 2012-10-14T22:02:02.843 回答