【问题标题】:Group By day and month Doctrine按日和月分组原则
【发布时间】:2023-04-01 21:42:01
【问题描述】:

我想按生日列出我的用户,所以是月份和日期,而不是年份。

我有这个问题

SELECT * 
FROM user 
WHERE birthDate IS NOT NULL 
GROUP BY MONTH(birthDate), DAY(birthDate)

但我不知道如何将它与 Symfony 和 Doctrine 一起使用。 我试过了

$result = $em->getRepository("AcmeApplicationBundle:SecurityServiceUser")
            ->createQueryBuilder('user')
            ->where('user.birthDate IS NOT NULL')
            ->groupBy('MONTH(user.birthDate), DAY(user.birthDate)')
            ->getQuery()
            ->getResult(); 

$result = $em->getRepository("AcmeApplicationBundle:SecurityServiceUser")
            ->createQueryBuilder('user')
            ->where('user.birthDate IS NOT NULL')
            ->groupBy('MONTH(user.birthDate)')
            ->groupBy('DAY(user.birthDate)')
            ->getQuery()
            ->getResult(); 

但在这两种情况下我都有一个错误

[语义错误] line 0, col 165 near 'MONTH(birthDate),':错误:无法按未定义的标识或结果变量分组。

【问题讨论】:

标签: php mysql sql symfony doctrine-orm


【解决方案1】:

您可以使用以下之一:

format(as.Date,) 

strftime(source, format)

【讨论】:

    【解决方案2】:

    您尚未为您的值设置别名。这是一个更新的版本:

       $result = $em->getRepository("AcmeApplicationBundle:SecurityServiceUser")
            ->createQueryBuilder('user')
            ->select(' user.username, MONTH(user.birthDate) AS gBmonth, DAY(user.birthDate) AS gBday')
            ->where('user.birthDate IS NOT NULL')
            ->groupBy('gBmonth')
            ->addGroupBy('gBday')
            ->getQuery()
            ->getResult(); 
    

    这应该可以正常工作。

    【讨论】:

    • 为什么一定要先选中才能分组
    • Ils 非常简单,就像在经典的 sql 查询中一样,您必须先在 select 中定义别名才能将其与 group 一起使用
    • 这会抛出这个错误,为什么? Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'my_database.o0_.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
    • 你还需要安装“composer require beberlei/DoctrineExtensions”
    • @elvismdev,这些链接可能有助于理解:1.) dev.mysql.com/doc/refman/8.0/en/group-by-handling.html。 2.) medium.com/@riccardoodone/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 2018-02-11
    相关资源
    最近更新 更多