选择查询问题

时间:2010-02-05 13:25:07

标签: sql mysql perl dbi

我在带有字段

的mysql数据库中有一个表

“name”,“title”,“cd_id”,“track”

条目如下所示:

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

为了获得每张CD的曲目(cd_id),我写了这个脚本:

#!/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;

是否可以使用适当的选择查询直接获得这些结果?

2 个答案:

答案 0 :(得分:2)

"SELECT cd_id, SUM(tracks) as tracks FROM my_table GROUP BY cd_id"

编辑:请点击此处了解有关GROUP BY的更多信息和其他事项:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

答案 1 :(得分:-1)

使用聚合函数

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