【问题标题】:Getting "#1111 - Invalid use of group function" without using GROUP in MySQL获取“#1111 - 组函数的无效使用”而不在 MySQL 中使用 GROUP
【发布时间】:2012-03-28 09:36:35
【问题描述】:
    $qb = $this->createQueryBuilder('t');

    return $qb
        ->join('t.customers', 'c')
        ->where($qb->expr()->eq('t.user', $user->getId()))
        ->andWhere($qb->expr()->gt($qb->expr()->count('c'), 0))
        ->orderBy('t.name')->getQuery()->getResult();

上面的查询(Doctrine2 生成的)给了我这个错误:

#1111 - Invalid use of group function

但奇怪的是我没有使用GROUP BY。非常感谢任何帮助,谢谢。

SELECT t0_.id AS id0,
       t0_.slug AS slug1,
       t0_.name AS name2,
       t0_.description AS description3,
       t0_.user_id AS user_id4
FROM tag t0_ 
    INNER JOIN customers_tags c2_ ON t0_.id = c2_.tag_id
        INNER JOIN customer c1_ ON c1_.id = c2_.customer_id
WHERE t0_.user_id = 1 AND COUNT(c1_.id) > 0
ORDER BY t0_.name ASC

【问题讨论】:

    标签: mysql sql doctrine doctrine-orm


    【解决方案1】:

    您在不允许的 where 子句中使用聚合函数 count()

    聚合函数的条件需要进入 HAVING 子句

    ....
    WHERE t0_.user_id = 1
    HAVING count(c1_.id) > 0
    

    当然你需要使用 GROUP BY 来获得正确的结果(虽然 MySQL 可能会让你侥幸不使用 GROUP BY - 但结果是不可预测的)

    【讨论】:

      【解决方案2】:

      没有必要加入和拥有。只需使用SIZE函数:

      $qb->where('SIZE(t.customers) = 0');
      

      这将为您提供所有没有附加客户的行

      【讨论】:

      • 先生,您成就了我的一天。自 24 小时以来一直在努力对数组集合进行双重检查(数组集合中的指定项或数组集合的大小为 0),这完美地解决了问题。
      【解决方案3】:

      "count"不能用在没有group by的地方,count是"group function"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-14
        • 2012-07-20
        • 2021-11-21
        • 2015-07-20
        • 2012-12-16
        • 1970-01-01
        相关资源
        最近更新 更多