Symfony - doctrine2中的子查询

时间:2016-08-01 08:06:23

标签: php mysql symfony doctrine-orm dql

我每月都有一组帖子。我需要一个数组,其中包含每个月发布的帖子的总记录(包括零)。 我没能在dql中写它:(任何想法PLZ?

示例数据:

+----+---------------------+
| id | date                |
+----+---------------------+
| 24 | 2012-12-16 16:29:56 |
|  1 | 2013-02-25 14:57:09 |
|  2 | 2013-02-25 14:59:37 |
|  4 | 2013-02-25 15:12:44 |
|  5 | 2013-02-25 15:14:18 |
|  7 | 2013-02-26 11:31:31 |
|  8 | 2013-02-26 11:31:59 |
| 10 | 2013-02-26 11:34:47 |
| 14 | 2013-03-04 04:39:02 |
| 15 | 2013-03-04 05:44:44 |
| 16 | 2013-03-04 05:48:29 |
| 19 | 2013-03-07 15:22:34 |
| 20 | 2013-03-15 12:24:43 |
| 21 | 2013-03-16 16:27:43 |
| 22 | 2013-03-16 16:29:28 |
| 23 | 2013-03-16 16:29:56 |
| 11 | 2013-03-17 11:35:12 |
+----+---------------------+

SQL查询:

SELECT count(b.id) as totalRec
FROM   (
            SELECT 'January' mnth
            UNION ALL
            SELECT 'February' mnth
            UNION ALL
            SELECT 'March' mnth
        ) a
        LEFT JOIN post b
            ON a.mnth = DATE_FORMAT(b.date, '%M') AND
               year(b.date) =  '2013' AND 
               DATE_FORMAT(b.date, '%M') IN ('January', 'February', 'March') 
GROUP  BY year(b.date)-month(b.date) 
ORDER  BY b.date ASC

输出

+----------+
| totalRec |
+----------+
|        0 |
|        7 |
|        9 |
+----------+

1 个答案:

答案 0 :(得分:0)

统计按月分组的所有帖子,并过滤掉您想要的月份:

SELECT count(*) as totalRec, DATE_FORMAT(b.date, '%m%Y') as month
FROM post b
WHERE month IN('012013', '022013', '032013')
GROUP BY month
ORDER BY b.date ASC

将导致:

+----------+----------+
| totalRec | month    |
+----------+----------+
|        0 |   012013 |
|        7 |   022013 |
|        9 |   032013 |
+----------+----------+