在Symfony 2中,我尝试进行子选择以从表中获取总计数。我每次收到以下错误:SQLSTATE[21000]: Cardinality violation: 1242 Subquery returns more than 1 row
。为什么我的声明中的GROUP BY不起作用?
$dql = " SELECT u.id as UserId, (
SELECT count(mtp.id)
FROM Site\MyBundle\Entity\MessageThread mtp
WHERE mtp.status=0
GROUP BY mtp.message
) as MessageThreadCountPending
FROM Site\UserBundle\Entity\Entity\User u
WHERE u.id=:id
";
示例MessageThread表
id | message | status | text
-------------------------------------------
1 | 1 | 0 | Blah blah blah
2 | 2 | 0 | Blah blah blah
3 | 2 | 0 | Blah blah blah
4 | 3 | 0 | Blah blah blah
期望的结果将由3
感谢您的反馈!
答案 0 :(得分:1)
一个简单的解决方法是删除子查询中的group by
:
SELECT u.id as UserId,
(SELECT count(mtp.id)
FROM Site\MyBundle\Entity\MessageThread mtp
WHERE mtp.status = 0
) as MessageThreadCountPending
FROM Site\UserBundle\Entity\Entity\User u
WHERE u.id = :id;
虽然这可以修复症状,但我怀疑你在子查询中需要某种关联子句。我猜是这样的:
WHERE mtp.status = 0 and mtp.user_id = u.id