MySQL:排除至少出现一次特定字段值的所有用户

时间:2013-04-09 19:26:32

标签: mysql

我正在尝试创建一个MySQL报告,其中仅包含学生用户和其他任何课程的教师。有时,用户可以是一门课程的学生,也可以是另一门课程的教师。我想从报告中完全排除该用户。

User Table
userid   username
  1        Bob
  2        John
  3        Sally
  4        Suzy



Courses Table
courseid   coursename
  100      Geometry
  101      Literature
  102      Spanish

Enrollments Table
userid   courseid   role
   1        100     student
   1        101     teacher
   2        100     student
   2        102     student
   3        101     student
   3        102     student
   4        100     student
   4        102     teacher

所需的输出是:

username    coursename     role
  John        Geometry     student
  John        Spanish      student
  Sally       Literature   student
  Sally       Spanish      student

Bob和Suzy不会被包括在内,因为他们至少在一门课程中担任教师角色。

SELECT u.username, c.coursename, e.role
FROM enrollments e
JOIN users u ON user.userid = e.userid
JOIN courses c ON c.courseid = e.courseid
WHERE e.role = 'student'

...不够具体,因为它包括Bob和Suzy的学生注册地。

我认为我应该以某种方式使用子连接,但这超出了我迄今为止所写的任何查询。谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

试试这个:

    select u.username,c.coursename,e.role
    from User as u
    inner join Enrollments as e
    on u.userid=e.userid
    inner join Courses as c
    on c.courseid=e.courseid
    -- where `condition`

使用Inner Join代替常规JOIN

答案 1 :(得分:0)

尝试

SELECT u.username, c.coursename, e.role
FROM enrollments e
JOIN users u ON user.userid = e.userid
JOIN courses c ON c.courseid = e.courseid
WHERE u.userid NOT IN (SELECT DISTINCT userid FROM enrollments WHERE role = 'teacher')