I'm just wandering is the following query valid. I have one table called professor which contains professors. Table subject contains subjects. Many-to-many relation is realized with professor_subject table, which contains professor_id and subject_id fields.
Now I need to see which professor is teaching which subject. I wrote this SQL query:
SELECT concat(professor.name, " ", professor.surname) as "Professor",
subject.name as "Subject"
FROM professor_subject, subject, professor
WHERE subject.id = subject_id
and professor.id = professor_id;
Is this query valid ? I mean, will it always do what I want ? I'm little suspicious because I didn't use JOIN keyword.
Thanks :)
No. There's nothing here that correlates a professor to a subject. You're using a cross join with no criteria (not sure if subject_id and professor_id in the where clause are table values or query parameters). You need something like:
select concat(professor.name, " ", professor.surname) as "Professor",
subject.name as "Subject"
from professor
inner join professor_subject
on professor.id = professor_subject.professor_id
inner join subject
on professor_subject.subject_id = subject.id
Assuming that subject_id and professor_id are in professor_subject, you're ok. Before the JOIN keyword was available in all versions of SQL (Oracle pre-9i for example), this was how joins were done.
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.