Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Perl/SQL query - grouping 'one to many' records

by pcdj_d (Initiate)
on Dec 09, 2008 at 23:11 UTC ( [id://729286]=perlquestion: print w/replies, xml ) Need Help??

pcdj_d has asked for the wisdom of the Perl Monks concerning the following question:

I have a situation where I have a table of incidents and a table of actions. The relationship is one incident has many actions.

I require the need to display via a web page, a list of incidents IDs and their relevant actions thus:

Indicent 1
- Action 1
- Action 2
- Action 3
Indicent 2
- Action 4
Incident 3
- Action 5
- Action 6

Currrently, I just retrieve a set of actions and can sort them by incident ID. However I would like each action grouped by incident, and the incident ID to be displayed just the once before each group of actions.

I currently have in one subroutine:
my $sql = " SELECT incident.id AS i_id, incident.severity, incident.summary, action.id AS a_id, action.incident_id, action.description, action.note +s FROM incident, action WHERE incident.id = action.incident_id AND action.due_date > $date (a specified date) AND action.due_date < current_date() ORDER BY sort_date ASC " $sth->prepare($sql); $sth->execute(); while (my $href =$sth->fetchrow_hashref()) { my $details={}; $details->{'Incident ID'} = $$href{'i_id'}; $details->{'Action ID'} = $$href{'a_id'}; $details->{'Severity'} = $$href{'severity'}; $details->{'Summary'} = $$href{'summary'}; and so on... push(my @results, $details); } return @results
And in another subroutine:
my @results = "first subroutine" foreach my $result (@results) { my $output = $result->{'Incident ID'}.", "; $output .= $result->{'Action ID'}.", "; $output .= $result->{'Severity'}.", "; $output .= $result->{'Summary'}.", "; and so on... $counter++ } return $output;
This will return something along the following lines:

1, 1, Severe, A severe incident
1, 2, Severe, A severe incident
1, 3, Severe, A severe incident
2, 4, Minor, A minor incident
2, 5, Minor, A minor incident

I would like something like:

1, Severe, A severe incident
-> 1 (action id, with further columns from the action table)
-> 2
-> 3
2, Minor, A minor incident
-> 4
-> 5

What's the easiest way to do this?

Replies are listed 'Best First'.
Re: Perl/SQL query - grouping 'one to many' records
by ahmad (Hermit) on Dec 09, 2008 at 23:26 UTC

    Just use SQL group by function.

    Few examples from MySQL website

      I was under the impression you couldn't 'group by' text fields? Which all these fields are (the figures '1,2,3' etc were just an example - they are all numeric IDs prefixed with some text.)

        Your impression is wrong, you can group by any field you want.


        www.jasonkohles.com
        We're not surrounded, we're in a target-rich environment!
Re: Perl/SQL query - grouping 'one to many' records
by duckyd (Hermit) on Dec 10, 2008 at 00:47 UTC
    I think the problem is mostly due to how you're storing the results as you fetch them from the database. If you use a hash keyed on incident.id and push the results for each action in, then the data will already be in the format you want to print it in. Here's an example:
    #!/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"; } }
    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:
    Incident: 1 - s 1 1: a 1 2: a 2 3: a 3 Incident: 2 - s 2 4: a 4 5: a 5
      Thanks duckyd, that worked a treat!

      One further question though - my results come out in a seemingly random order and cannot be sorted in any way. I believe this is due to the nature of hashes, and you can't guarantee in which order they are returned.

      Is there any simple way of modifying this so that I can have some control over how the results are sorted when displayed on screen? Something as simple as sorting by $i_id would be good!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://729286]
Approved by ikegami
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-04-25 08:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found