0

我正在尝试创建一个 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 在他们是学生的地方的注册。

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

4

2 回答 2

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

于 2013-04-09T19:29:32.577 回答
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')
于 2013-04-09T19:37:13.660 回答