【问题标题】:GROUP_CONCAT with JOINLEFT in Zend Db SelectZend Db Select 中的 GROUP_CONCAT 和 JOINLEFT
【发布时间】:2012-04-22 14:08:21
【问题描述】:

假设我有 2 张桌子

articles
  id              title
  1               Article 1
  2               Article 2


Images
  id              article_id     image
  1               1              a.png
  2               1              b.png
  3               2              c.png
  4               2              d.png

我想要的只是检索所有带有图片的文章。

例如:

article_id     title           images
1              Article 1       a.png, b.png
2              Article 2       c.png, d.png

如何使用 Zend_Db_Select 做到这一点?

我尝试过这样的事情,但没有运气:

$select = $this->getDbTable()->select()->setIntegrityCheck(false)->distinct();
$select->from(array('a'=>'articles'))
  ->joinLeft(array('i'=>'images'),'i.article_id=a.id',array('images'=> new
               Zend_Db_Expr('GROUP_CONCAT(i.image)')));

它只返回 1 行,其中 'images' 字段包含两篇文章的图像。

article_id     title           images
1              Article 1       a.png, b.png, c.png, d.png

我在这里做错了什么?

【问题讨论】:

    标签: mysql zend-framework left-join group-concat zend-db-select


    【解决方案1】:

    您没有在查询中使用group by 子句。

    试试下面:

    $select->from(array('a'=>'articles'))
      ->joinLeft(
           array('i'=>'images'),
           'i.article_id=a.id',
           array('images'=> new Zend_Db_Expr('GROUP_CONCAT(i.image)')))
      ->group('a.id');
    

    【讨论】:

    • 添加“GROUP BY”解决了这个问题。或者使用它也可以解决它: $select->joinLeft(array('x'=> new Zend_Db_Expr('(SELECT i.article_id, GROUP_CONCAT(i.image) as images FROM images as i GROUP BY i.article_id)') ), 'x.article_id=a.id', array('x.images'));
    • 你的回答对我很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多