replacing a programming loop with the correct JOIN Please help a programmer do this in a more SQL-like manner.
I have database with 4 tables related in a sort of tree: progs,
events, questions, answers. Each row in each table has a unique ID:
prog_id, event_id, question_id,answer_id. Each row in the bottom
three tables (not progs) knows the id of the table above it. For
example, every answer knows the question_id it associates with, and
every question knows the event_id it associates with.
The programmer in me selects all the categories and loops through the
results. For example, for each prog I select all the events and loop
through them to find the questions, etc. See the issue? With the
proper join I should be able to select all the information at once,
one row for every row in the bottom 'answers' table.
There are additional conditions, simulated by 'where
progs.status="initializing" '
This is the select I came up with:
select progs.title, progs.prog_id, events.title, events.event_id,
questions.content, questions.question_id, answers.content,
answers.answer_id from progs INNER JOIN (events,questions,answers) on
(progs.prog_id=events.prog_id AND events.event_id=questions.event_id
AND questions.question_id=answers.question_id) where
progs.status="initializing" order by
progs.prog_id,events.event_id,questions.question_i d,answers.answer_id;
can one of y'all gurus advise me whether this will always give me one
line for each answer, provided the relationships are correct?
Thanx!
-- clh |