带有HAVING的子查询中的教义COUNT

时间:2017-09-21 10:03:28

标签: php mysql sql doctrine-orm doctrine

我正在尝试获取排行榜的用户排名列表。我有三张桌子:

  • 用户(id,用户名)
  • 电路(id,名称)
  • user_circuits(id,user,circuit,record)

记录计算正确,但我总是得到用户总数而不是排名。这是我的问题:

$query = $em->createQuery('
    SELECT
        u.id AS id,
        u.username AS username,
        COALESCE(MAX(c.record), 0) AS record,
        (
            SELECT
                COUNT(DISTINCT u2.id)
            FROM ApplicationSonataUserBundle:User u2
            LEFT JOIN u2.circuits c2
            HAVING COALESCE(MAX(c2.record), 0) > record
        ) AS ranking
    FROM ApplicationSonataUserBundle:User u
    LEFT JOIN u.circuits c
    GROUP BY id, username
    ORDER BY record DESC
');

$leaderboard = $query
    ->setMaxResults($max)
    ->getArrayResult()
;

结果如下:

UserRepository.php on line 88:
array:20 [
  0 => array:4 [
    "id" => 427
    "username" => "ninety-nine"
    "record" => "99"
    "ranking" => "102"
  ]
  1 => array:4 [
    "id" => 426
    "username" => "ninety-eight"
    "record" => "98"
    "ranking" => "102"
  ]
  2 => array:4 [
    "id" => 425
    "username" => "ninety-seven"
    "record" => "97"
    "ranking" => "102"
  ]
  3 => array:4 [
    "id" => 424
    "username" => "ninety-six"
    "record" => "96"
    "ranking" => "102"
  ]
  4 => array:4 [
    "id" => 423
    "username" => "ninety-five"
    "record" => "95"
    "ranking" => "102"
  ]
]

0 个答案:

没有答案