我在mysql数据库中有一个带有字段的表
“名称”,“标题”,“ cd_id”,“曲目”
条目如下所示:
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;
是否可以通过适当的选择查询直接获得这些结果?
最佳答案
"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
关于sql - 选择查询问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2207434/