tags:

views:

70

answers:

2

Hello! I have a table in a mysql-database with the fields

"name", "title", "cd_id", "tracks"

The entries look like this:

Schubert | Symphonie Nr 7 | 27 | 2
Brahms | Symphonie Nr 1 | 11 | 4
Brahms | Symphonie Nr 2 | 27 | 4
Shostakovich | Jazz Suite Nr 1 | 19 | 3

To get the tracks per cd (cd_id) I have written this script:

#!/usr/bin/env perl
use warnings; use strict;
use DBI;

my $dbh = DBI->connect( 
    "DBI:mysql:database=my_db;", 
    'user', 'passwd', { RaiseError => 1 } );

my $select_query = "SELECT cd_id, tracks FROM my_table";

my $sth = $dbh->prepare( $select_query );
$sth->execute;

my %hash;
while ( my $row = $sth->fetchrow_hashref ) {
    $hash{"$row->{cd_id}"} += $row->{tracks};
}

print "$_ : $hash{$_}\n" for sort { $a <=> $b } keys %hash;

Is it possible to get these results directly with an appropriate select query?

+2  A: 
"SELECT cd_id, SUM(tracks) as tracks FROM my_table GROUP BY cd_id"

edit: see here for further information and other things you can do with GROUP BY: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

Mike Sherov
A: 

use an aggregate function

  SELECT `cd_id`, SUM(`tracks`) AS s
    FROM `your_table`
GROUP BY `cd_id`
knittl
count will get the number of rows for each cd_id, not the sum of the tracks column.
Mike Sherov
you can't use SUM(*), you need to provide the column you want to sum up.
Mike Sherov
hm, you are right
knittl