如何从MySQL表中按状态及日期分组获取指定格式记录?
嘿,这就帮你把给定的MySQL表数据整理成两种分组格式的记录数组!先把源数据清晰列出来:
| id | name | status | updated |
|---|---|---|---|
| 1 | John | Active | 2018-04-12 |
| 2 | Peter | Active | 2018-04-12 |
| 3 | Kenny | Inactive | 2018-04-13 |
| 4 | Mike | Active | 2018-04-14 |
| 5 | Neeth | Pending | 2018-04-14 |
| 6 | Kenith | Inactive | 2018-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
相关产品推荐
相关产品推荐

