在使用 Mysql 5.7 版本将我的数据库迁移到 CloudDB 后,我在 symfony 4 中遇到了查询构建器的问题。
以下代码适用于 mysql 5.6
public function findRecentReviews($max): array
{
$qb = $this->createQueryBuilder('r')
->andWhere('r.active = :active')
->setParameter('active', 1)
->setMaxResults($max)
->groupBy('r.website')
->orderBy('r.id', 'ASC')
->getQuery();
return $qb->execute();
}
在 5.7 中我遇到了这个错误
An exception has been thrown during the rendering of a template ("An >exception occurred while executing 'SELECT r0_.id AS id_0, r0_.comment AS >comment_1, r0_.author AS author_2, r0_.email AS email_3, r0_.added AS >added_4, r0_.ip AS ip_5, r0_.active AS active_6, r0_.hide_in_latest AS >hide_in_latest_7, r0_.rate AS rate_8, r0_.website_id AS website_id_9 FROM >review r0_ WHERE r0_.active = ? GROUP BY r0_.website_id ORDER BY r0_.id ASC >LIMIT 3' with params [1]:
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of >SELECT list is not in GROUP BY clause and contains nonaggregated column >'ps_main.r0_.id' which is not functionally dependent on columns in GROUP BY >clause; this is incompatible with sql_mode=only_full_group_by").*
我无法禁用 ONLY_FULL_GROUP_BY 模式,因为我没有 super 用户权限。
如果我不能禁用 ONLY_FULL_GROUP_BY 并且我不能降级 mysql 版本,我的查询应该是什么样子?
最佳答案
MySQL 5.7.5 及更高版本实现了函数依赖检测。
如果启用了ONLY_FULL_GROUP_BY
SQL 模式(默认情况下),MySQL 将拒绝满足select list
, HAVING
条件的查询或 ORDER BY
列表指的是既未在 GROUP BY
子句中命名也不在功能上依赖于它们的非聚合列。
有两种选择。
1:禁用 SQL 模式 only_full_group_by
:您可以通过执行以下查询来检查:
SHOW VARIABLES LIKE '%sql_mode%';
Output:
sql_mode 'STRICT_ALL_TABLES,NO_ZERO_IN_DATE,ONLY_FULL_GROUP_BY'
通过从 sql_mode
变量中删除 ONLY_FULL_GROUP_BY
,在 mysql 中禁用 only_full_group_by
。
SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
2:更新您的查询:
SELECT name, ANY_VALUE(address), MAX(age) FROM t GROUP BY name;
关于php - 如何将 GROUP_BY 与查询构建器和 mySQL >= 5.7 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57790508/