sql - 从 DBIx::Class 中的多个表中选择

标签 sql perl dbix-class

我有以下 DBIx::Class 代码:

my $where = 'me.loginid = ? AND me.code = ?';
my @bind  = ( $loginID, $code );
my $tip_signals = $bom_schema->resultset('Table1')->search_literal(
    $where, @bind,
    {
        join => 'table2',
        group_by => [ 'me.id' ],
        '+select' => [ {'count' => '*'}, 'table2.id' ],
        '+as'     => [ 'Count', 'ID' ],
    });

根据上述DBIx::Class代码生成以下SQL语句:

SELECT me.id, me.loginid, me.tipster_date, me.code, me.short_code_without_payout, COUNT( * ), table2.id 

FROM table1 me LEFT JOIN table2 table2 ON table2.tip_signals_id = me.id 

WHERE ( 
me.loginid = 'yccheok' AND me.code = 'ALIBABA_CODE' 
) 

GROUP BY me.id

现在,我希望获得 4 个表的结果。我手动编写自己的 SQL 代码:

SELECT me.id, me.loginid, me.tipster_date, me.code, me.short_code_without_payout, COUNT( * ), table2.id 

FROM table1 me, table2, referrers, affiliates 

WHERE ( 
me.loginid = 'yccheok' AND me.code = 'ALIBABA_CODE'

and table2.tip_signals_id = me.id
and referrers.affiliates_id = affiliates.id
and affiliates.loginid = me.loginid
and referrers.loginid = table2.loginid
) 

GROUP BY me.id

我尝试将上面的 SQL 语句转换为 DBIx::Class,如下所示:

my $where = 'me.loginid = ? AND me.code = ? AND table2.tip_signals_id = me.id AND referrers.affiliates_id = affiliates.id AND affiliates.loginid = me.loginid AND referrers.loginid = table2.loginid';
my @bind  = ( $loginID, $code );
my $tip_signals = $bom_schema->resultset('Table1')->search_literal(
    $where, @bind,
    {
        from        =>  [ {table2=>'table2'}, {referrers=>'referrers'}, {affiliates=>'affiliates'} ],
        group_by    =>  [ 'me.id' ],
        '+select'   =>  [ {'count' => '*'}, 'table2.id' ],
        '+as'       =>  [ 'Count', 'ID' ],
    });

当我尝试对结果集执行next时,出现异常“不是数组引用”。请注意,我不允许在 DBIx::Class 中使用 join,因为 referrersaffiliates 表与 *table 没有关系*** 表。

如何获得与 SQL 多选表等效的 DBIx::Class 代码?

最佳答案

如果 table1/2 和引用者/附属机构之间没有关系,那么为什么不在 DBIx::Class 结果类中创建它们呢?

您没有粘贴这些内容,所以我在这里进行猜测,您想将这样的内容添加到您的 Table1 类中:

__PACKAGE__->has_many('affiliates', 'MyDB::Schema::Affiliate', 'loginid');

在表2中:

__PACKAGE__->has_many('referrers', 'MyDB::Schema::Referrer', 'loginid'); 

修改这些类名称以匹配您的实际类。

我猜测您使用了 Schema::Loader 来加载表,但它没有为您创建这些表,因为您的数据库没有设置适当的外键? DBIx::Class 并不关心,您可以很高兴地在其中建立更多关系,这些关系不是实际的 FK,并且它将创建您需要的联接。

HTH。

关于sql - 从 DBIx::Class 中的多个表中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/784438/

相关文章:

perl - DBIx::Class 与 HTML::FormHandler 重用 dbh

database - DBIx::Class 获取 dbh

mysql - 按特定 ID 删除一行,该行不存在于另一个表列 ID 中

mysql - Perl 和 MYSQL - 选择年-月-日小时 :minute:seconds (unix? ) 样式时间戳之间的数据

perl - 在 Perl 中打印固定列表的最佳方法(使用下划线而不是空格)

perl - 使用文件的内容作为程序的参数

perl - 我可以从工具包模板文件中搜索结果集吗?

php - 检查 SELECT mysql php 上的寄存器总和

sql - 查找时间戳之间的间隙

sql - Mysql DateTime 组按 15 分钟