我在此上花费了太多时间,但仍然无法使语法正常工作。
在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文档时,它提到“工会”已被弃用。使用'literal'DBIx::Class是行不通的,因为它只能用作where子句。我不想使用视图(另一个建议),因为SQL最终将被扩展以匹配其中一个ID。如何格式化此查询以在DBIx::Class中工作?谢谢。

最佳答案

通过在子查询结果集上使用as_query方法,DBIx::Class非常方便地支持子查询。食谱中有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/],
});

关于perl - DBIx::Class中的子查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25312506/

10-09 03:18