You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从MySQL表中按状态及日期分组获取指定格式记录?

嘿,这就帮你把给定的MySQL表数据整理成两种分组格式的记录数组!先把源数据清晰列出来:

idnamestatusupdated
1JohnActive2018-04-12
2PeterActive2018-04-12
3KennyInactive2018-04-13
4MikeActive2018-04-14
5NeethPending2018-04-14
6KenithInactive2018-04-15

接下来分两种分组方式给你展示结果:

1. 按status分组的记录数组

如果你想用SQL直接生成结构化结果,可以用MySQL的JSON函数来聚合:

SELECT 
  status, 
  JSON_ARRAYAGG(JSON_OBJECT('id', id, 'name', name)) AS grouped_records
FROM your_table
GROUP BY status;

最终整理成对象格式如下(以JavaScript风格为例):

{
  'Active': [
    { id: 1, name: 'John' },
    { id: 2, name: 'Peter' },
    { id: 4, name: 'Mike' }
  ],
  'Inactive': [
    { id: 3, name: 'Kenny' },
    { id: 6, name: 'Kenith' }
  ],
  'Pending': [
    { id: 5, name: 'Neeth' }
  ]
}
2. 按updated日期分组的记录数组

同样用SQL聚合的话,语句如下:

SELECT 
  updated, 
  JSON_ARRAYAGG(JSON_OBJECT('id', id, 'name', name, 'status', status)) AS grouped_records
FROM your_table
GROUP BY updated;

对应的最终对象格式:

{
  '2018-04-12': [
    { id: 1, name: 'John', status: 'Active' },
    { id: 2, name: 'Peter', status: 'Active' }
  ],
  '2018-04-13': [
    { id: 3, name: 'Kenny', status: 'Inactive' }
  ],
  '2018-04-14': [
    { id: 4, name: 'Mike', status: 'Active' },
    { id: 5, name: 'Neeth', status: 'Pending' }
  ],
  '2018-04-15': [
    { id: 6, name: 'Kenith', status: 'Inactive' }
  ]
}

如果是在应用层处理(比如Python、PHP),只需要先查询所有数据,然后遍历每条记录,根据status或updated的值作为键,把记录追加到对应键的数组里就行,逻辑超直观~

内容的提问来源于stack exchange,提问作者Rupesh Ranjan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:57:45