I have several tables from which I need to display data.
Schools
-------
id | Title
Programs
--------
id | descr | title | type | school.id
Granted, not the best set up but there isn’t any thing I can do about the database structure.
I need to create a list, seperated by School, Program, and Program Type. Right now, I have a big huge nested loop (pseudo code):
Select * from Schools
For Each School
print $school_header;
Select Program Type from Programs WHERE School.id = $school_id
For Each Program type
print $type_header;
Select * from Programs where School.id = $school_id and type = $program_type
For Each Program
print $program_link;
Needless to say its a big mess.
The end result is a list:
- Program 1
- Program Type 1
- Program
- Program
- Program Type 2
- Program
- Program
- Program Type 3
- Program
- Program Type 1
Is there a way to do this with fewer queries and less code that isn’t so database intensive?
The real issue here is not whether one or the other programming language is more efficient. The vast, vast difference in performance is due to data locality, namely that executing the query on the database itself doesn’t require you to move all of the data back and forth over the wire for evaluation, whereas the PHP solution does.
For your query, what you want to do is write a stored procedure which returns multiple result sets (for further joining in PHP) or a single large result set (by joining in SQL). My guess would be that it would look something like:
This will give you the large rectangular array, ordered by each title in order of priority. This way you can loop through rows until you see the School title change, or the Program Type title change, or whatever, and render the appropriate closing tags.