加入最近的兄弟,类型= 1

时间:2015-01-14 08:34:46

标签: mysql join dql siblings closest

我有一张桌子" sf_messages"存储门票和答案:

CREATE TABLE IF NOT EXISTS `sf_messages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` bigint(20) unsigned DEFAULT NULL,
  `answered_by` bigint(20) unsigned DEFAULT NULL,
  `parent_id` int(11) DEFAULT NULL,
  `last_child_id` int(11) DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `type` smallint(6) NOT NULL COMMENT '1 = Question, 2 = Answer',
  PRIMARY KEY (`id`),
  UNIQUE KEY `UNIQ_C375BE71A5038785` (`last_child_id`),
  KEY `IDX_C375BE71A76ED395` (`user_id`),
  KEY `IDX_C375BE713948559F` (`answered_by`),
  KEY `IDX_C375BE71727ACA70` (`parent_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=51740;

我的前端用户可以发票,我的管理员可以回复。这张票的所有者也能够回复。

  • parent_id用于儿童存储原始票证。
  • last_child_id用于将最后一条消息存储在会话中的原始消息
  • 类型用于区分前端和后端消息(1 =前端,2 =后端)
  • user_id始终存储会话的前端用户
  • answers_by存储消息的作者(如果type = 1,则为前端用户,如果type = 2,则为后端用户)

所以它就像一个对话,一张原始票和一些儿童留言。

- Original ticket (from User 1)
| - Answer #1 (from Admin 1)
| - Answer #2 (from User 1)
| - Answer #3 (from Admin 1)
| - Answer #4 (from User 1)
| - Answer #5 (from Admin 2)

出于统计目的,我想获得来自前端用户的消息和来自管理员的答案之间的平均持续时间,由管理员用户分组。

我试过这个,但我理解JOIN是不正确的,因为答案加在原始邮件上,而不是来自前端用户的最近的邮件。

public function fetchTotalAnswerDurationInSecondsByUserInDateRange(\Evo\UserBundle\Entity\User $user = null, array $range)
{
    $qb = $this->createQueryBuilder('m')
        ->select('SUM(TIME_TO_SEC(TIMEDIFF(m.createdAt, q.createdAt)))')
        ->join('EvoBackendBundle:Message', 'q', 'WITH', 'm.parent = q')
        ->where('m.type = 2')
    ;

    if( !is_null($user) ) {
        $qb->andWhere('m.answeredBy = :user')
            ->setParameter('user', $user);
    }

    if( $range['start'] ) {
        $qb->andWhere('m.createdAt >= :start')
            ->setParameter('start', $range['start']);
    }

    if( $range['end'] ) {
        $qb->andWhere('m.createdAt <= :end')
            ->setParameter('end', $range['end']);
    }

    return $qb->getQuery()->getSingleScalarResult();
}

我可以使用&#34; type&#34;来区分前端和后端消息。领域。 1 =前端消息,2 =后端消息。我想我也必须处理像WHERE MAX(q.created_at) < m.created_at这样的事情,但我不知道如何继续。 任何帮助将不胜感激。

0 个答案:

没有答案