Monday, March 31, 2008

Grouping Query Output

OK, so this post won't relate to all, however for the coders in the group, it's a useful piece of information.

ColdFusion has an attribute that you can add on to a cfoutput tag called "group=". What this does is allow you to group the query results by a particular field. I will put down a couple of examples, the first one being how I generally would code the page, and the second will use the group attribute.



SELECT *
FROM tblCourse c
ORDER BY courseName




SELECT *
FROM tblStudent
WHERE cID=#cID#

#get.courseName#



  • #get2.studentName#





So, this will generate output something like this:

Course 1
Keith Ginter
Paul Plato

Course 2
Chris Clapton
Jeff Coomber

Now, this is the correct way to do it, using the group attribute of the cfoutput tag



SELECT c.*, s.studentName
FROM tblCourse c
INNER JOIN tblStudent s on c.id=s.cID
ORDER BY c.courseName


#get.courseName#



  • #get.studentName#





This will generate the same output as before, however the code is alot slicker and you save trips to the database to pull the results of the student names as done in the first example.

I have a training video on the above, as well as a number of other CF tricks. I will make those available once they are all ready to go.

1 comment:

PJ Plato said...

Being a cfml programmer this is definitely a cool and helpful tip. However, I don't see any cfml tags in the code that show how the group attribute is use. Could you please provide a full code example cause I could use this in many of our web projects.