Question : Minimizing Database Queries and CFOutput

Hi Folks,

Here's the scenario - I'm outputting 'status updates' and comments for each on a single page (similar to Facebook, if you like).

The status updates are currently returned with the following query;

<cfquery name="livestream" datasource="#datasource#">
SELECT s.sID, s.wUserID, s.sStatus, s.sCreatedDate, u.FirstName, u.Surname
FROM statusupdates s
LEFT JOIN users u
ON s.wUserID=u.wUserID
ORDER BY s.sCreatedDate DESC
</cfquery>

I have an additional table, 'comments' with the following fields - cID, inreplyto,wUserID & cComment.  In this case the value for 'inreplyto' would match 'sID' in the first query (pointing to the comment being in reply to that status update).

At the moment, the only way I can see of displaying comments for each update is to do a cfquery against the comments table during the cfoutput query for the updates.  I know I can add an extra query to the first query to count the number of comments, but I can't figure out a way of both returning the comments themselves, and actually outputting them on screen using a single query (I would assume, if I can return everything within one query, I would use cfoutput query to return the statuses, then a cfloop for the comments).

Am I being ambitious in hoping to achieve this in a single query?  I'm using MySQL

Answer : Minimizing Database Queries and CFOutput

If I'm understanding correctly ... yeah, you could retrieve both updates and comments in 1 query.

The exact sql depends on which columns you need to display in the output. But in general terms, just add a JOIN to the comments table and add the "cComment" column to your select list.

    SELECT s.sID, s.wUserID, s.sStatus, s.sCreatedDate, u.FirstName, u.Surname, c.cComment
    FROM   statusupdates s
                      LEFT JOIN users u  ON s.wUserID=u.wUserID
                      LEFT JOIN comments c ON c.inreplyto = s.sID
    ORDER BY s.sCreatedDate DESC, s.sID

You could group the comments beneath each update by using cfoutput's "group" attribute.  Just be sure to ORDER BY and "group" by the same columns or it won't work properly.

       <cfoutput query="yourQuery" group="sID">
                 <!--- show status only once --->
                  #sStatus#<br>
                 <!--- show individual comments --->
                 <!--- NOTE: Using nested <cfoutput> tags is deliberate!! --->
                 <cfoutput>#cComment#</cfoutput>
       </cfoutput>
Random Solutions  
 
programming4us programming4us