mysql获取按日期分组的所有帖子

v1uwarro  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(346)

我想得到我的数据库中的所有职位,并让他们返回,按日期分组(年->月->日->这一天的职位)。
我当前的数据库结构: ID, author, title, content, created_at 可能的值可以是:

1, 1, "hello world", "This is the content", "2020-07-27 09:15:57"
2, 1, "Another post", "Another post content", "2020-07-27 11:09:55"
3, 1, "Third post", "No content", "2020-07-28 08:15:20"
...etc

我想实现的是,获得所有这些帖子,但按日期(年、月、日)对它们进行分组。即。:

[2020] => [
   [7] => [
      [27] => [
         [ID] => 1,
         [ID] => 2,
      ],
      [28] => [
         [ID] => 3,
      ]
   ]
]

到目前为止我试过的: SELECT id FROM my_posts_table WHERE author = 1 GROUP BY created_at ORDER BY created_at ASCSELECT id, YEAR(created_at) as year, MONTH(created_at) as month, DAY(created_at) as day FROM my_posts_table WHERE author = 1 GROUP BY year, month, day ORDER BY year, month, day ASC 我的预期结果将是我想要实现的上述例子。但实际上我得到的是:

[0] => [
   [ID] => 1,
   [year] => 2020,
   [month] => 7,
   [day] => 27
],
[1] => [
   [ID] => 3,
   [year] => 2020,
   [month] => 7,
   [day] => 28
]

我现在完全糊涂了,因为我以为“组员”的工作方式和我预期的一样,但它的工作方式似乎不同。
你们能给我指出正确的方向吗?我希望我的目标很明确。但如果不是,这里又是:“我想从author\u id=1的\u posts表中获取所有帖子,并按年->月->日->帖子返回”,因此“27”天的所有帖子都应该在[27]键下。。
编辑:我按要求做了一把小提琴

bmp9r5qi

bmp9r5qi1#

使用组\u concat
对于sqlfiddle示例,请尝试以下方法:

SELECT GROUP_CONCAT(id), 
YEAR(created_at) as year, MONTH(created_at) as month, DAY(created_at) as day 
FROM my_posts_table 
WHERE author = 1 
GROUP BY year, month, day ORDER BY year, month, day ASC
cbwuti44

cbwuti442#

数据库查询总是返回由行和列组成的“平面”结果集。如果您想要嵌套数据结构,那么一种方法是编写一个标量查询,只返回一行和一列包含json对象。
这将涉及多个级别的聚合和json函数 JSON_ARRAYAGG() 以及 JSON_OBJECT() :

select json_object(created_year, json_arrayagg(obj)) obj
from (
    select 
        created_year, 
        json_object(created_month, json_arrayagg(obj)) obj      
    from (
        select 
            year(created_at)  created_year,
            month(created_at) created_month, 
            json_object(day(created_at), json_arrayagg(id)) obj
        from my_post_table
        group by year(created_at), month(created_at), day(created_at)
    ) t
    group by created_year, created_month
) t

相关问题