Let’s say we want to display the name of each student who is enrolled in a course and the names of the courses they are enrolled in.
Since the name of the student, and the name of the course exist in two different tables (
courses respectively), we need to use
JOIN to combine the two tables.
The query will look like this
Observe closely, and you can figure out the basic syntax of a
SELECTpart: specify the list of columns you need, just like list of columns you mention in normal
SELECTqueries, but this time, specifying the table from which each column is picked before it, with a
dot(.) operator. Eg.
FROMpart: list of tables the columns are being picked from, separated by the word
students JOIN courses
ONpart: This is key part of a
JOINquery. It is used to express the columns from each table which should be matched together to connect the data amongst them. In this case, the column
studentsstores the reference to the courses students are enrolled in, in the form of
idfrom the actual
idcolumn from the
coursestable. Hence, the clause,
ON students.courseId = courses.id