2012-10-31 40 views
1

我有一个MySQL标准查询,我需要转换为Zend_Db_Select但我无法让它工作。MySQL查询Zend DB选择

我得到这个错误:

Select query cannot join with another table 

这里的查询:

// 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() 
      ) 
     ); 

如果有人可以转换这一点,那将是伟大的,因为我需要在select()模式,因为我用Zend_Pagination

对于那些想要完整的PHP函数:Pastebin和堆栈跟踪:Pastebin

回答

1

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

​​
+0

我得到一个'错误1064'。'SQLSTATE [42000]:语法错误或访问冲突:1064您的SQL语法错误;检查对应于你的MySQL服务器版本“为'x' ON x.post_id = p.id ORDER BY'created_date' DESC LIMIT 10”附近使用的线2' –

1

正如迈克尔已经提到的,你需要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()magic method并向您显示您的查询。

1

该表达式是Count(*)声明,而不是整个子查询。

​​

我不是很确定你真的需要有一个子查询。无论从一个简单的连接开始,并建立它。

//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'); 

一旦你的查询与默认工作,就可以完善它,直到它的工作你想怎么。

如果您正在查询使用paginator a count()表达式是无用的,因为paginator会为每个查询应用限制和偏移。

你也可以考虑以相反的方式执行这个查询。您可能会更好地加入其他方向,或仅在评论表上执行查询。没有看到你的结构的其余部分,这很难说。

祝你好运。

+0

嗯正确的语法手册,我忘了指定分页程序仅用于对博客帖子进行分页。整个事情更多地是使用连接或其他东西来计算每条帖子的评论...... –

+0

那么,为什么只需要根据需要使用where()和post_id(可能是外键或至少一个索引)来进行查询。个人而言,我只希望用getComments()方法从实体模型,但它并不像你的结构来支持。 – RockyFord

+0

NOP,我不支持那种模式。但是,我和帖子之间的链接并不是一个外键,它只是一个参考。 –

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; 

它完美的工作!

+0

恭喜,KISS似乎总是最好的工作。 – RockyFord