我有一个非常复杂的SQL查询,可以在创建故障单和支持团队的第一条消息之间获得延迟平均值:
SELECT u.username,
AVG(((
SELECT UNIX_TIMESTAMP(tm.added_at)
FROM ticket_message tm
INNER JOIN `fos_user` tmu ON tm.author_id = tmu.id
LEFT JOIN `fos_user_user_group` tmug ON tmu.id = tmug.user_id
LEFT JOIN `fos_group` tmg on tmug.group_id = tmg.id
WHERE tm.ticket_id = t.id
AND (tmu.roles LIKE '%ROLE_SUPPORT%' OR tmg.roles LIKE '%ROLE_SUPPORT%')
ORDER BY tm.added_at LIMIT 1
) - UNIX_TIMESTAMP(t.added_at))) / 60 as delay
FROM `fos_user` u
INNER JOIN `ticket` t on u.id = t.assigned_id
GROUP BY u.id
此查询就是这样的。我想用DQL做同样的事情。我试过了:
$averageQb = $this->prepareUserTopQB();
$averageQb
->innerJoin('u.assignedTickets', 't', Join::WITH, 't.addedAt BETWEEN :begin AND DATE_ADD(:end, 1, \'DAY\')')
->addSelect('AVG(('.$messageQb->getDQL().') - UNIX_TIMESTAMP(t.addedAt)) / 60 as average')
->orderBy('average')
;
使用Expr:
$averageQb = $this->prepareUserTopQB();
$averageQb
->innerJoin('u.assignedTickets', 't', Join::WITH, 't.addedAt BETWEEN :begin AND DATE_ADD(:end, 1, \'DAY\')')
->addSelect(
$averageQb->expr()->quot(
$averageQb->expr()->avg($averageQb->expr()->diff(
$messageQb->getDQL(),
'UNIX_TIMESTAMP(t.addedAt)'
)),
60
).' as average'
)
->orderBy('average')
;
但是这两种方法都有这个错误:
[1/2] QueryException: SELECT u.id user_id, u.username, u.firstname, u.lastname, u.email, AVG(SELECT tm.addedAt FROM AppBundle:TicketMessage tm INNER JOIN tm.author tma LEFT JOIN tma.groups tmg WHERE tm.id = t.id AND (tma.roles LIKE '%ROLE_SUPPORT%' OR tmg.roles LIKE '%ROLE_SUPPORT%') ORDER BY tm.addedAt ASC - UNIX_TIMESTAMP(t.addedAt)) / 60 as average FROM AppBundle\Entity\User u INNER JOIN u.groups g WITH g.name = 'Support' INNER JOIN u.assignedTickets t WITH t.addedAt BETWEEN :begin AND DATE_ADD(:end, 1, 'DAY') GROUP BY u ORDER BY average ASC
[2/2] QueryException: [Syntax Error] line 0, col 71: Error: Expected Literal, got 'SELECT'
我必须使用DQL,但Doctrine似乎不喜欢在普通函数中选择。
如何解决这个问题?
由于