Doctrine DQL添加了一个选择列,导致only_full_group_by错误

时间:2018-04-03 14:13:14

标签: mysql doctrine-orm dql

我有这个用DQL编写的查询:

SELECT
    p
FROM
    Plan p
LEFT JOIN
    p.requests r
WHERE
    p.endsAt > :now
    AND p.organization = :organization
GROUP BY p.id
HAVING SUM(CASE WHEN r.isAccepted IS NULL THEN 0 ELSE r.isAccepted END) = 0
ORDER BY p.id DESC

这是一个分页符。 在对paginator进行迭代时,我有以下错误:

  

SQLSTATE [42000]:语法错误或访问冲突:1055 Expression#16   SELECT列表不在GROUP BY子句中并包含nonaggregated   栏' o1_.is_accepted'这不是功能上的   依赖于GROUP BY子句中的列;这是不相容的   的sql_mode = only_full_group_by"。)

由于Doctrine在生成SQL查询时添加了一列(o1_.is_accepted AS is_accepted_15),在select子句中(简化而没有paginator的COUNT操作):

SELECT o0_.id AS id_0, o0_.average_hourly_rate AS average_hourly_rate_1, o0_.teacher_to_contact_count AS teacher_to_contact_count_2, o0_.starts_at AS starts_at_3, o0_.ends_at AS ends_at_4, o0_.reference AS reference_5, o0_.bac_plus3 AS bac_plus3_6, o0_.created_at AS created_at_7, o0_.is_paid AS is_paid_8, o0_.paid_at AS paid_at_9, o0_.teacher_who_accepted_count AS teacher_who_accepted_count_10, o0_.unit_price_excluding_vat AS unit_price_excluding_vat_11, o0_.billed_amount AS billed_amount_12, o0_.description AS description_13, min(o1_.is_accepted) AS sclr_14, o1_.is_accepted AS is_accepted_15
FROM organization_teacher_request_plan o0_
LEFT JOIN
    organization_teacher_request o1_
    ON o0_.id = o1_.plan_id
WHERE
    o0_.ends_at > ?
    AND o0_.organization_id = ?
GROUP BY o0_.id
HAVING SUM(CASE WHEN o1_.is_accepted IS NULL THEN 0 ELSE o1_.is_accepted END) = 0

没有sql模式" only_full_group_by"它工作正常。但我想将此查询修复为迁移到MySQL 5.7的最佳实践。

自添加MIN(r.isAccepted)字段以来,添加o1_.is_accepted无效。

编辑:它是DQL查询的HAVING SUM(CASE WHEN r.isAccepted IS NULL THEN 0 ELSE r.isAccepted END) = 0部分,它在select子句中添加了相应的字段,一个学说错误?

2 个答案:

答案 0 :(得分:0)

我不了解DQL并且从未使用它,但语法看起来与HQL非常相似,SELECT p可能正在返回整个Plan实体,包括所有列,一些其中没有出现在GROUP BY条款中。如果您只选择p.id,那么ONLY_FULL_GROUP_BY错误就会消失:

SELECT p.id
FROM Plan p
LEFT JOIN p.requests r
...

答案 1 :(得分:0)

我认为此查询的问题在于使用HAVING子句执行过滤器,然后需要在SQL中添加该字段。

另一种方法是使用子查询(具有反向查询和NOT EXISTS子句)来完成相同的任务,如下所示:

os.system

更多信息:https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/dql-doctrine-query-language.html#dql-select-examples