ZF2:有条件地从另一个表中计数

时间:2015-03-08 12:51:20

标签: sql zend-framework2

我有两个表,通知和分析。

通知已获得列:id

Analytics已获得列:type,notification_id

在我的NotificationTable模型中,我需要查询所有通知,并返回当type =" notification"时,notification_id = id的次数计数。

我想我必须加入分析,并使用计数表达式,但由于某种原因我只得到一行,计数无效。

$select->from($this->table)
      ->columns(array('*' ,'sum_view' => new \Zend\Db\Sql\Expression('sum(CASE analytics.type = "notification" WHEN TRUE THEN 1 ELSE 0 END)'),
        'view_count' => new \Zend\Db\Sql\Expression('count(analytics.notification_id)')))
      ->join('analytics' , 'notification.id = analytics.notification_id', array('type', 'notification_id'), 'right')
      //->group('notification.id')
      ->order('notification.id DESC');

任何帮助?

1 个答案:

答案 0 :(得分:0)

  1. 使用where过滤type =“notification”
  2. 的行
  3. 删除grouporder,额外selectjoin参数
  4. 使用COUNT DISTINCT来防止重复

  5. $select->from($this->table)
           ->columns(array('*' ,'cnt' => new \Zend\Db\Sql\Expression('COUNT(DISTINCT notification.id)'))
           ->join('analytics' , 'notification.id = analytics.notification_id')
           ->where(array('analytics.type' => 'notification'));