0

Here is a brief summary of my database tables involved:

Courses

  • CourseId
  • SchoolId
  • DisciplineId
  • Name

Schools

  • SchoolId
  • Name

Disciplines

  • DisciplineId
  • Name

(there are other columns in the tables, but they're not really relevant to the question)

I'm trying to select all of the Courses where Courses.SchoolId = a given SchoolId, the name of said school from Schools, the names of all of the disciplines associated with each course, and sort by Disciplines.Name. If this summary doesn't make sense, perhaps my query will:

 $prep = $pdo->prepare('SELECT Courses.*, Disciplines.Name as Discipline, Schools.Name as School
                        FROM Courses
                        JOIN Courses AS C ON Courses.SchoolId = :schoolId
                        AND Schools ON Schools.SchoolId = :schoolId
                        AND Disciplines ON Disciplines.DisciplineId = Courses.DisciplineId
                        ORDER BY Disciplines.Name ASC');
$prep->bindParam(':schoolId', $schoolId, PDO::PARAM_INT);

if(!$prep->execute()){
    print_r($pdo->ErrorInfo());
}

Here is the error:

Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ON Schools.SchoolId = '115773' AND Disciplines ON Disciplines.Disciplin' at line 4 in /Users/foremanjordan/Web Dev/Cleerly/src/scripts/addCourse.php on line 24

I cannot for the life of me figure out why this is. I'm still fairly new to using JOINs, so I'm sure that it has something to do with my ignorance, but from what I've understood thus far, this should work?

Also, as a sort of side question, does anyone understand why I would have to alias Courses in the first JOIN line? I get a non-unique error otherwise, but I don't understand why.

Thank you!

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Jordan Foreman
  • 3,848
  • 7
  • 40
  • 65

1 Answers1

2

use the specified keyword JOIN not AND

SELECT Courses.*, 
       Disciplines.Name as Discipline, 
       Schools.Name as School
FROM   Courses
       INNER JOIN Schools 
          ON Courses.SchoolId = Schools.SchoolId
       INNER JOIN Disciplines 
          ON Disciplines.DisciplineId = Courses.DisciplineId
WHERE  Courses.SchoolId = :schoolId
ORDER  BY Disciplines.Name ASC

When sorting, use ORDER BY not SORT

To further gain more knowledge about joins, kindly visit the link below:

John Woo
  • 258,903
  • 69
  • 498
  • 492
  • Thanks! That worked like a charm! I'll have to read that article. Most of what I found was fairly difficult to grasp, even though I understand the concept, and so I've been trying to learn by doing w/ trial and error. Also, thanks for pointing out the `SORT` thing. I haven't been writing queries for a long time, and keep forgetting my basic syntax! – Jordan Foreman Apr 12 '13 at 03:34