MySQL三通三角查询

时间:2012-10-14 21:16:02

标签: mysql

我有一个团队,学校和作业的数据库。选择作业后,学校(无论如何用户)可以在作业中添加一个团队,以便他们可以开始分配作业。 ER图如下所示: ER-diagram of the database 重要提示:即使数据库的设置另有建议,团队< - >赋值关系为1:N。一个团队只能处理一项任务。这是通过ORM系统控制的。

现在这里有一个问题:数据库中有团队负责不属于他们学校的作业:学校选择作业,创建团队并删除他们的作业选择。我需要找到这种情况的学校(身份证,姓名)。

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

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;

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

1 个答案:

答案 0 :(得分: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
      )