2012-02-23 43 views
0

有什么建议吗?任何人都解决过这个问题?如何将使用多个连接和子查询的SQL查询转换为Perl DBIx :: Class?

select c.parent_id, c.category_id, c.name, count(*) 
    from categories c 
    join product_categories pc 
    on c.category_id  = pc.category_id 
    join authorizations a 
    on pc.product_id  = a.product_id 
    join set_authorizations sa 
    on a.authorization_id = sa.authorization_id 
where a.active   = 1 
    and sa.set_id   = 2 
    and c.parent_id in (
    select category_id 
     from categories 
    where parent_id is null 
     ) 
group by c.parent_id, c.category_id, c.name;

在此先感谢...

+1

您是否已经为表和外键创建了DBIx :: Class定义? – dgw 2012-02-23 18:44:33

回答

2

你要找的东西,是不是很容易实现的。正如dgw所说的,你必须首先做一些家庭作业,定义你的模型对象 - 用DBIx :: Class或者Rose :: DB :: Object,或者你喜欢的任何ORM。只有这样,使用这些对象才能成为一项简单的任务,无论它们有多复杂。

但还有另一种方法:使用SQL :: Abstract模块及其“扩展”,SQL :: Abstract :: More。如果你只需要抽象你的查询,使他们'完美'而不是'sqlish',我想这正是医生的命令。 )

例如,在SQL查询::摘要::更多听起来像是说:

my ($sql, @bind) = $sqla->select(
    -columns => [ qw/c.parent_id c.category_id c.name COUNT(*)/ ], 
    -from => [-join => qw/ 
     categories|c 
      category_id=category_id product_categories|pc 
      product_id=product_id  authorizations|a 
      authorization_id=authorization_id set_authorizations|sa 
     /], 
    -where => { 
    'a.active' => 1, 
    'sa.set_id' => 2, 
    'c.parent_id' => \["IN (SELECT category_id FROM categories WHERE parent_id IS NULL)"], 
    }, 
    -group_by => [qw/ c.parent_id c.category_id c.name /], 
); 

这仍然相当艰巨,但...也许创造了所有的连接表将使VIEW代码(和,我想,性能)更容易消化? )