gpt4 book ai didi

perl - DBIx::Class 中的子查询

转载 作者:行者123 更新时间:2023-12-01 13:47:09 24 4
gpt4 key购买 nike

我在这上面花了太多时间,但仍然无法使语法正常工作。
在 DBIx::Class 中可以使用这个 select 语句吗?

"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 文档时,它提到“联合”已被弃用。使用“文字” DBIx::Class 不起作用,因为它仅用作 where 子句。我不想使用 View (另一个人的建议),因为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com