我在查询时遇到了一些麻烦。首先,我将快速解释我需要对这些表格做些什么:
用户(ID,用户名)和来电(id,user_id [fk],结果)
结果字段指的是该调用发生的事情(错误,超时,忙碌,谈话......)。
我想为每个用户制作一个条形图,显示总呼叫,错误呼叫,超时呼叫等。
这是我的代码:
parser_count_separators
我遇到的问题是编写该子查询语法。我尝试使用$em = $this->get('doctrine')->getManager();
$calls = $em->getRepository('CRMBundle:Call\Call')
->createQueryBuilder('e')
->addSelect('o.username as user')
->addSelect('COUNT(DISTINCT e.id) as total_calls')
->addSelect('SUBQUERY for error_calls')
->addSelect('SUBQUERY for timeout_calls')
....
->join('e.user', 'o');
$calls = $calls->groupBy('o.username')
->orderBy('e.id', 'ASC')
->getQuery()
->getResult();
,但它无效。
希望您在此提出一些建议,谢谢!
答案 0 :(得分:1)
您的子查询需要加入外部查询。让我们在正常的SQL术语中考虑一下firs
SELECT count(c.id) as total_calls
, (SELECT count(*)
FROM calls
WHERE user_id = u.id -- Here's the join w/the outer query
AND result = 'ERROR'
) as error_calls
, (SELECT count(*)
FROM calls
WHERE user_id = u.id
AND result = 'TIMEOUT'
) as timeout_calls
FROM calls c
LEFT JOIN user u
ON u.id = c.user_id
GROUP BY u.id
;
因此,在DQL术语中,单个子查询看起来像这样
SELECT count(errors)
FROM CRMBundle:Call\Call error
WHERE error.user = o // Again, here is the join w/the outer query
AND error.result = 'whatever'
回到查询构建器上下文,我们有了这个
->addSelect('(SELECT count(errors) FROM CRMBundle:Call\Call error WHERE error.user = o AND error.result = :error_result) AS error_calls')
->setParameter('error_result', 'ERROR')
答案 1 :(得分:0)
您可以在查询中添加其他groupBy类型吗?
->groupBy('o.username')
->addGroupBy('e.result')