我想进一步查询,但不确定如何

时间:2015-07-20 12:42:43

标签: mysql sql

MySQL表格图:

enter image description here

我的查询到目前为止:

SELECT tblcourses.CourseStandard,
                tblcourses.CourseID,
                tblcourses.CourseRef,
                tblcourses.CourseStandard,
                tblcourses.CourseName,
                tblcourses.CourseDuration,
                tblcourses.NQFLevel,
                tblcourses.CoursePrice,
                tblcoursestartdates.StartDate
  FROM etcgroup.tblcoursestartdates tblcoursestartdates
       INNER JOIN etcgroup.tblcourses tblcourses
          ON (tblcoursestartdates.CourseID = tblcourses.CourseID)
 WHERE tblcoursestartdates.StartDate >= Now()

如果查看图表,您会看到我有第3张表格。上面的查询工作正常。它显示所有数据。

我想展示所有课程及其各自的日期,不包括学生已预订的课程。请记住,1个课程可以有20个开课日期。这就是为什么我只选择日期> = Now()。

我想确保学生不会被双重预订。是的我之后可以做到。哔哔的学生已经预订但是如果我现在可以显示学生已经预订的课程日期那么好。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

courseID bookingIDnull的{​​{1}}上进行左边连接到tblBookings(没有匹配项)。您必须提供studentID作为查询的参数。

SELECT DISTINCT c.CourseStandard,
                c.CourseID,
                c.CourseRef,
                c.CourseStandard,
                c.CourseName,
                c.CourseDuration,
                c.NQFLevel,
                c.CoursePrice,
                d.StartDate
FROM etcgroup.tblcoursestartdates d
INNER JOIN etcgroup.tblcourses c ON d.CourseID = c.CourseID
LEFT JOIN etcgroup.tblBookings b on c.CourseID = b.CourseID and b.StudentID = @StudentID
WHERE d.StartDate >= Now() and b.bookingID is null

答案 1 :(得分:1)

这非常简单。大概你知道你想看到的StudentID。左边连接到预订表并选择不匹配。

     SELECT tblcourses.CourseStandard,
            tblcourses.CourseID,
            tblcourses.CourseRef,
            tblcourses.CourseStandard,
            tblcourses.CourseName,
            tblcourses.CourseDuration,
            tblcourses.NQFLevel,
            tblcourses.CoursePrice,
            tblcoursestartdates.StartDate
       FROM etcgroup.tblcoursestartdates tblcoursestartdates
 INNER JOIN etcgroup.tblcourses tblcourses 
              ON tblcoursestartdates.CourseID = tblcourses.CourseID
             AND tblcoursestartdates.StartDate >= Now()
  LEFT JOIN tblbookings
              ON tblbookings.CourseId = tblcourses.CourseId
             AND tblbookings.StudentId = <<<the student ID in question >>>
      WHERE tblbookings.BookingID IS NULL

这里的技巧是LEFT JOIN ... IS NULL模式。它消除 LEFT JOIN的ON条件所在的行,只留下它错过的行。

答案 2 :(得分:0)

使用NOT EXISTS或NOT IN查找学生已预订的课程:

@echo off
Cls
:top
Echo %random% %random% %random% %random% %random% %random%
Goto top