mysql5.7 json 类型字段的聚合统计问题

2021-01-27 17:17:32 +08:00
 xuyl
DROP TABLE IF EXISTS `abc`;
CREATE TABLE `abc` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `score` json DEFAULT NULL,
  `type` varchar(10) COLLATE utf8mb4_bin DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

INSERT INTO `abc` (`id`, `score`, `type`) VALUES
(1,	'{\"v\": 100, \"type\": \"number\"}',	'a'),
(2,	'{\"v\": 95, \"type\": \"number\"}',	'a'),
(3,	'{\"v\": 60, \"type\": \"number\"}',	'a'),
(4,	'{\"v\": 100, \"type\": \"number\"}',	'b'),
(5,	'{\"v\": 95, \"type\": \"number\"}',	'b'),
(6,	'{\"v\": 60, \"type\": \"number\"}',	'b');

执行 sql 语句

select type, max(score->'$.v') as v1, min(score->'$.v') as v2 from abc group by type;

得出结果

+------+------+------+
| type | v1   | v2   |
+------+------+------+
| a    | 95   | 100  |
| b    | 95   | 100  |
+------+------+------+

不是预期

type=a, v1=100, v2=60
type=b, v1=100, v2=60

查了下,可能 mysql 的 json 字段索引方式是按照 ascii 码顺序索引的,那么该怎么做才能得到预期结果呢?

1217 次点击
所在节点    程序员
5 条回复
ily433664
2021-01-27 17:30:37 +08:00
转成数字
select type, max(CONVERT(score->'$.v', DECIMAL)) as v1, min(CONVERT(score->'$.v', DECIMAL)) as v2 from abc group by type;
Rache1
2021-01-27 17:47:05 +08:00
```sql
select type, max(CAST(score->'$.v' AS unsigned)) as v1, min(CAST(score->'$.v' AS unsigned)) as v2 from abc group
by type;
```
xuyl
2021-01-27 17:53:30 +08:00
@ily433664 @faqqcn 测试都可以,多谢两位。
xuyl
2021-01-28 12:06:04 +08:00
@ily433664 现在又遇到新问题,如果数值为浮点数,则会丢失精度
ily433664
2021-01-28 14:11:30 +08:00
@xuyl #4 设置 DECIMAL 的精度,DECIMAL(18, 2)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/748980

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX