0

I've a ('courses') table that has a HABTM relationship with ('instructors') table through another table...

I want to get the data of an instructor with all related courses in one query..

Currently, I have the following SQL:

SELECT *
FROM `instructors` AS `instructor`
LEFT JOIN `courses` AS `course`
  ON `course`.`id` IN (
    SELECT `course_id`
    FROM `course_instructors`
    WHERE `course_instructors`.`instructor_id` = `instructor`.`id`
    )
WHERE `instructor`.`id` = 1

This SQL does what it should be doing, the only "problem" I have is that I get multiple rows for each joined rows.

My question is:
Can I get the result I want in one query? Or do I have to manipulate the data in PHP?

I'm using PHP and MySQL.

1
  • (Has and belongs to many/many-to-many) relation... Commented Apr 5, 2011 at 12:48

3 Answers 3

1

Each record of a query result set has the same format: same number of fields, same fields, same order of fields. You cannot change that.

Sign up to request clarification or add additional context in comments.

Comments

1
SELECT *
FROM instructors AS instructor
LEFT JOIN
     course_instructors
ON
     instructor.id= course_instructors.instructor_id
LEFT JOIN
      courses
ON
       course_instructors.course_id =  course.id
WHERE instructor.id = 1

This assumes the PK of course_instructors is (instructor_id,course_id)

Explanation of query:

  1. First join + WHERE make sure you get the relevant instructor
  2. Second join matches ALL the entries from the course_instructor table that belongs to this instructor. If none found, will return one row with NULL in all fields
  3. Last join matches all relevant courses from the entries found from course_instructor If none would will return one record with NULL in all fields.

Again: important to use the right constraints to avoid duplicate data.

1 Comment

I can not see a difference in the result between my query and yours... I'm still getting more than one row for the instructor I'm querying...
0

That's the nature of relational databases. You need to get the instructor first and then get the related courses. That's how I would do it and that's how I've been doing it. I'm not sure if there is a "hack" to it.

1 Comment

This is what I was doing too... I'm just want to know if there is a way to do it with SQL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.