in reply to Perl/SQL query - grouping 'one to many' records
note that the last foreach, where the printing happens, is pretty straightforward - loop over the keys (one for each incident), print the incident info, and then loop through the actions for each. The output looks like this:#!/usr/local/bin/perl use strict; use warnings; my @query = ( { i_id => 1, summary => 's 1', a_id => 1, description => 'a 1', }, { i_id => 1, summary => 's 1', a_id => 2, description => 'a 2', }, { i_id => 1, summary => 's 1', a_id => 3, description => 'a 3', }, { i_id => 2, summary => 's 2', a_id => 4, description => 'a 4', }, { i_id => 2, summary => 's 2', a_id => 5, description => 'a 5', }, ); my %results; # analagous to your while ( my $href = $sth->fetchrow_hashref() ){ while( my $href = shift @query ){ # treat each entry in %results as a hash ref unless( $results{ $href->{ i_id } } ){ # save the summary information in the summary key $results{ $href->{ i_id } }->{ summary } = $href->{ summary }; } # push a hash ref of action information into { actions } push @{ $results{ $href->{ i_id } }->{ actions } }, { a_id => $href->{ a_id }, desc => $href->{ description }, }; } # now it's grouped by incident, and you can print it: foreach my $i_id ( keys %results ){ print "Incident: $i_id - $results{ $i_id }->{ summary }\n"; foreach my $action ( @{ $results{ $i_id }->{ actions } } ){ print " $action->{ a_id }: $action->{ desc }\n"; } }
Incident: 1 - s 1 1: a 1 2: a 2 3: a 3 Incident: 2 - s 2 4: a 4 5: a 5
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl/SQL query - grouping 'one to many' records
by pcdj_d (Initiate) on Dec 11, 2008 at 09:14 UTC |