mysql - 在 DQL 中加入并计数

标签 mysql doctrine doctrine-orm symfony dql

我有一个 MySQL 命令,但我找不到 DQL 中的等效命令。我正在尝试获取评论最多的帖子列表。这是 MySQL 命令:

SELECT posts.id, COUNT(comments.id) AS num
FROM posts
LEFT JOIN comments ON ( posts.id = comments.post_id )
GROUP BY posts.id

结果如下:

id  num
1   8
2   9
3   17
4   7
5   6
6   20
7   7
8   10
9   14
10  7

在 DQL 中,它应该是:

SELECT post, COUNT(comment.id) AS num
FROM Entity\Post post
LEFT JOIN post.comments comment
GROUP BY post.id

但这给出了:

id  num
1   50
2   0
3   0
4   0
5   0
6   0
7   0
8   0
9   0
10  0

我不明白 50 是从哪里来的,以及为什么这两个结果之间存在差异。你能告诉我如何使这个连接在 Doctrine 中起作用吗?

最佳答案

我做了一些测试,发现一切似乎都很好。

Video: id, title, ...
Comment: id, video_id, content, ...

数据库模式非常简单,我认为不需要任何解释。

#DQL:
    SELECT v.id, COUNT(c.id) AS num
    FROM Video v
    JOIN v.comments c
    GROUP BY v.id
    ORDER BY num DESC

#Generated SQL:
    SELECT v0_.id AS id0, COUNT(v1_.id) AS sclr1 
    FROM video v0_ 
    INNER JOIN video_comment v1_ ON v0_.id = v1_.video_id 
    GROUP BY v0_.id 
    ORDER BY sclr1 DESC

#Result set:
    Array
    (
        [0] => Array
            (
                [id] => 148
                [num] => 3
            )

        [1] => Array
            (
                [id] => 96
                [num] => 2
            )

        [2] => Array
            (
                [id] => 111
                [num] => 1
            )

        [3] => Array
            (
                [id] => 139
                [num] => 1
            )

    )

如果您选择整个 Video 对象而不是它的 id(v 而不是 SELECT 中的 v.id子句)查询也将执行。当然,在第 0 元素下会有一个 Video 对象,而不是 id 元素。

在 Doctrine 2.1.0-DEV 上测试

关于mysql - 在 DQL 中加入并计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6326284/

相关文章:

mysql : Can I recreate a table using select, 内部联接和 where 子句在一步中?

php - Doctrine 更新 -- Mysql Errno : 150

php - DQL : Class '(' is not defined 中的嵌套子查询错误

php - 在 Doctrine DBAL 中重用 QueryBuilder

performance - 使用 Doctrine 2.1 EXTRA_LAZY 关联加快分页

php - Doctrine - Query One-To-Many, Unidirectional with Join Table association from inverse side

mysql - sql中的json单值条件

php - 我只想显示日期为空的数据

mysql - XML 到 MySQL : Only adding half of the items?

php - Windows 上 Symfony 5.0.1 控制台中已弃用的类警告