1

I have a MySQL standard query that I need to convert into a Zend_Db_Select but I can't get it to work.

I get this error:

Select query cannot join with another table

Here's the query:

// THE COUNTER
$subselect = $this->table->select()->from(
        array('x' => 'blog_comments'),
        array('x.post_id', new Zend_Db_Expr('count(*) as comments')))
    ->group('post_id');
// THE TOTAL SELECT
$select->from(array('p' => 'blog_posts'), array('p.*'))
       ->setIntegrityCheck(false)
       ->joinLeft(array(
           'x' => $subselect,
           'x.post_id = p.id', 
           array()
           )
       );

If someone can convert this, it would be great because I need that in select() mode because I use Zend_Pagination.

For those who want the full PHP function: Pastebin and the stack traces: Pastebin.

4

4 回答 4

1

表达式是Count(*)语句,而不是整个子查询。

$subselect = $this->table->select()->from(
    array('x' => 'blog_comments'),
    array('x.post_id', new Zend_Db_Expr('count(*) as comments'))
)->group('post_id');

$select->from(array('p' => 'blog_posts'), array('p.*'))
    ->joinLeft(array(
        'x' => $subselect,
        'x.post_id = p.id', 
        array()
    ));

我不确定你是否真的需要一个子查询。无论如何,从一个简单的加入开始并以此为基础。

//getGateway = whatever method used to access the database adapter.
//SetIntegrityCheck(false) locks the tables from writes allowing tables to be joined
$select = $this->getGateway()->select()->setIntegrityCheck(false);
$select->from('blog_posts');//default $cols = *
$select->join('blog_comments', 'blog_comments.post_id' = 'blog_posts.post_id');//does it really matter what kind of join you use? They all work the same so use whichever you like.
$select->group('blog_comments.post_id');

一旦你得到使用默认值的查询,你可以对其进行细化,直到它按你想要的方式工作。

如果您正在执行查询以使用分页器,那么count()表达式是无用的,因为分页器将对每个查询应用限制和偏移量。

您也可以考虑反向执行此查询。您最好加入另一个方向,或者只在评论表上执行查询。如果没有看到你的结构的其余部分,这很难说。

祝你好运。

于 2012-10-31T11:36:57.700 回答
1

您可能需要:setIntegrityCheck(false)- 查看: http: //framework.zend.com/manual/1.12/en/zend.db.select.html了解更多信息

$select = $this->select()
->from(params) 
->setIntegrityCheck(false) 
->joinLeft(params)
->where(params);
于 2012-10-31T09:19:28.043 回答
1

正如 Michael 已经提到的,您需要setIntegrityCheck(false)使用Zend_Db_Select.

Error 1064有点模棱两可,包含各种查询语法问题。所以我建议你把子查询用括号括起来:

$select->setIntegrityCheck(false)
    ->from(array('p' => 'blog_posts'), array('p.*'))
    ->joinLeft(array(
        'x' => new Zend_Db_Expr("({$subselect})"), 
        'x.post_id = p.id', 
        array()
    ));

如果不起作用,那么您的子选择一定有问题。试试echo $subselect;哪个会调用__toString() 魔术方法并向您显示您的查询。

于 2012-10-31T10:03:01.193 回答
0

我终于以另一种方式做到了。

CMW_Model_Comments在视图中使用我的帖子 ID 来获取评论数。

// IN MY VIEW
echo $this->commentor->getCommentCount($post->id);

// IN MY CONTROLLER
$cmt = new CMW_Model_Comments();
$this->view->commentor = $cmt;

它完美地工作!

于 2012-10-31T12:54:34.477 回答