开发者

Select query question

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

"na开发者_Go百科me", "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?


"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


Use an aggregate function

  SELECT `cd_id`, SUM(`tracks`) AS s
    FROM `your_table`
GROUP BY `cd_id`
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜