SQL概念:嵌套循环

时间:2014-10-19 11:50:42

标签: mysql sql

  1. Teacher (userID, name, DOB, gender, email, address, phoneNo, password, highestQual, isAdmin)
  2. Lesson (lessonID, lessonFee, <teacherID>, <subjectID>)
  3. Enroll (<studentID>, <lessonID>, <paymentID>,result)
  4. 假设运行以下SQL将返回两个具有相同teacherID的元组。

    SELECT teacherID FROM tuition.Lesson WHERE lessonID IN(
                    SELECT lessonID FROM tuition.Lesson WHERE lessonID NOT IN ((
                    SELECT distinct lessonID FROM tuition.Enroll ))
                    ); 
    

    enter image description here

    但是如果我想选择要显示的名称,结果将返回一个元组而不是两个元组。

    SELECT name FROM tuition.teacher WHERE userID IN (
                    SELECT teacherID FROM tuition.Lesson WHERE lessonID IN(
                    SELECT lessonID FROM tuition.Lesson WHERE lessonID NOT IN ((
                    SELECR distinct lessonID FROM tuition.Enroll )))
                    );  
    

    我可以做什么,以便我的结果显示两个元组,同一个名称显示两次。请帮忙指教。

1 个答案:

答案 0 :(得分:0)

tuition.teacher只有userID teacher1的记录,所以你得到一条记录。这完全正确。您应该在第一个查询中使用distinct子句,以获得teacherID

之类的唯一SELECT distinct teacherID FROM tuition.Lesson ...

如果您强烈要复制结果,请使用{/ 1}}子句,如

UNION