MySQL JSON 查询的问题!求大佬解答!

2019-10-22 14:26:29 +08:00
 0x666666

这是我的表结构 +-------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+-------+ | customer_id | bigint(20) | NO | PRI | NULL | | | field_value | json | YES | | NULL | | | object_type | varchar(255) | YES | | NULL | | +-------------+--------------+------+-----+---------+-------+ 这是我存到数据库的数据,json 格式: { "customerId": 1, "objectType": "BUILDING", "fieldValue": "[{"fieldName":"客户名称","fieldType":"SINGLE_TEXT","required":true,"systemField":true},{"fieldName":"客户联系方式","fieldType":"SINGLE_TEXT","required":true,"systemField":true},{"fieldName":"客户标签","fieldType":"LABEL","required":true,"systemField":true,"values":["有钱","賊鸡儿任性","牛 B"]}]" } 我想查出 fieldValue 中的每个字段: select customer_id as customerId, object_type as objectType, json_extract(field_value, '$.fieldName') as fieldName, json_extract(field_value, '$.desc') as fieldDesc, json_extract(field_value, '$.required') as required, json_extract(field_value, '$.fieldType') as fieldType, json_extract(field_value, '$.systemField') as systemField from field where customer_id = 1 and object_type = 'BUILDING';

然后得到一堆空的值: +------------+------------+-----------+-----------+----------+-----------+-------------+ | customerId | objectType | fieldName | fieldDesc | required | fieldType | systemField | +------------+------------+-----------+-----------+----------+-----------+-------------+ | 1 | BUILDING | NULL | NULL | NULL | NULL | NULL | +------------+------------+-----------+-----------+----------+-----------+-------------+

3964 次点击
所在节点    MySQL
1 条回复
0x666666
2019-10-22 15:17:39 +08:00
已经解决了,查不出数据的原因是 json 是个数组,需要用'$[0].fieldName'这种来取才能取到值,或者'$[*].fieldName'

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

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

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

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

© 2021 V2EX