DBIx :: Class中的子查询

时间:2014-08-14 15:58:42

标签: perl dbi catalyst dbix-class

我花了太多时间在这上面,仍然无法使语法工作。 这个select语句在DBIx :: Class中是否可行?

"SELECT A.id, A.name, count(C.a_id) AS count1, 
   (SELECT count(B.id FROM A, B WHERE A.id=B.a_id GROUP BY B.a_id, A.id) AS count2
 FROM A LEFT OUTER JOIN C on A.id=C.a_id GROUP BY C.a_id, A.id"

下面这段代码在DBIx :: Class中工作以提取表'C'的计数,但是我多次努力添加表'B'的计数一再失败:

     my $data= $c->model('DB::Model')
                    ->search({},
                            {
                                    join => 'C',
                                    join_type => 'LEFT_OUTER',
                                    distinct => 1,
                                    'select' => [ 'me.id','name',{ count => 'C.id', -as => 'count1'} ],
                                    'as' => [qw/id name count1 /],
                                    group_by => ['C.a_id','me.id'],
                            }
                    )
                    ->all();

我试图在一个查询中获得两个计数,以便将结果保存在一个数据结构中。在另一个论坛上,有人建议我进行两次单独的搜索调用,然后将结果联合起来。当我查看DBIx :: Class文档时,它提到'union'已被弃用。使用'literal'DBIx :: Class不起作用,因为它只是用作where子句。我不想使用视图(另一个建议),因为SQL最终会扩展为匹配其中一个id。如何格式化此查询以在DBIx :: Class中工作?谢谢。

1 个答案:

答案 0 :(得分:2)

DBIx :: Class通过在子查询结果集上使用as_query方法非常方便地支持子查询。食谱中有some examples。对于您的用例,它看起来像:

# your subquery goes in its own resultset object
my $subq_rs = $schema->resultset('A')->search(undef, {
  join => 'B',
  group_by => [qw/A.id B.id/],
})->count_rs;

# the subquery is attached to the parent query with ->as_query
my $combo_rs = $schema->resultset('A')->search(undef, {
    select => [qw/ me.id me.name /,{ count => 'C.id' }, $subq_rs->as_query],
    as => [qw/ id name c_count b_count/],
});