简体   繁体   中英

PHP / MySQL Query within a query

Hello I have a table which has a list of school courses. (schoolcourses) The table gets inner joined with another table of instructors that are assigned to that course (instructors).

So far easy.

The complex part is within the same query I need to get the status of the instructor. There is another table called course_acceptance_history. So when an instructor is assigned a course he accepts the course. And it inserts a record into course_acceptance_history.

An insturctor CAN accept, then deny a course, then another instructor can ACCEPT the same course. So in other words course_acceptance_history can have 10 entries for the same course.

How do i pick the MOST RECENT record for a course from course_acceptance_history during the query that gets all the courses?

This is what my query looks like but i think i need a sub query to pull only the record from course_acceptance_history with the highest ID for that course and instructor ID

Example

    SELECT * FROM schoolcourses

INNER JOIN instructors ON schoolcourses.courseinstructor = instructors.instructorsid
INNER JOIN course_acceptance_history ON schoolcourses.schoolcoursesid = course_acceptance_history.courseid

I guess I need to merge the query above with

SELECT * FROM course_acceptance_history WHERE instructorid=$insid AND courseID=$courseID ORDERBY ID DESC
SELECT * FROM schoolcourses
    INNER JOIN instructors ON
        schoolcourses.courseinstructor = instructors.instructorsid
    INNER JOIN course_acceptance_history ON
        schoolcourses.schoolcoursesid = course_acceptance_history.courseid
WHERE course_acceptance_history.id =
    (SELECT id
        FROM course_acceptance_history
        WHERE instructorid=instructors.id
        AND courseID=schoolcourses.schoolcoursesid
        ORDER BY ID DESC
        LIMIT 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM