Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more efficient: a SQL JOIN or nested PHP loop?

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

Is there a way to do this with fewer queries and less code that isn't so database intensive?

like image 367
Oranges13 Avatar asked Jul 26 '26 16:07

Oranges13


1 Answers

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:

SELECT S.Title as School_Title, pt.title as Program_type_title, p.title as Program_Title
FROM School S 
INNER JOIN ProgramType pt on s.id = pt.school_id
INNER JOIN Program p on pt.id = p.program_type_id
ORDER BY S.Title, pt.title, p.title

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.

like image 69
Chris Shain Avatar answered Jul 28 '26 04:07

Chris Shain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!