我有一个表名"广告系列"。其中一列名为" filter_apps"他的类型是 JSON
我有文件行,它们只包含这样的标记数组:
["be3beb1fe916ee653ab825fd8fe022", "c130b917983c719495042e31306ffb"]
["4fef3f1999c78cf987960492da4d2a"]
["106c274e319bdeae8bcf8daf515b1f"]
["2521f0df6cffb7487d527319674cf3"]
["c130b917983c719495042e31306ffb"]
示例:
SELECT JSON_SEARCH(filter_apps, 'one', 'c130b917983c719495042e31306ffb') FROM campaigns;
结果:
"$[1]"
null
null
null
"$[0]"
现在一切都正确,匹配的列回来了。如果我做一个测试,我可以证明:
SELECT JSON_EXTRACT(filter_apps, '$[1]') FROM campaigns;
结果
"c130b917983c719495042e31306ffb"
null
null
null
null
所以在这一点上我想我可以使用JSON_EXTRACT提取值,我的查询:
SELECT JSON_EXTRACT(filter_apps, JSON_SEARCH(filter_apps, 'one', 'c130b917983c719495042e31306ffb')) FROM campaigns;
这导致我出错:
" [42000] [3143]无效的JSON路径表达式。错误在字符位置1附近。"
答案 0 :(得分:7)
<强>解强>
简单:
SELECT JSON_EXTRACT(filter_apps, JSON_UNQUOTE(JSON_SEARCH(filter_apps, 'one', 'c130b917983c719495042e31306ffb'))) FROM campaigns;
问题解决了!我将JSON_SEARCH包装在JSON_UNQUOTE方法中!
小小的提示,我在这里找到了解决方案:https://dev.mysql.com/doc/refman/5.7/en/json-function-reference.html
答案 1 :(得分:1)
我花了几个小时,因为我的 JSON 对象要复杂得多,但我找到了“全部”选项的解决方案。
SELECT *,
REPLACE(REPLACE(LTRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(filter_apps, ',', n), ',', -1)), '[', ''), ']', '') AS all_json
FROM (
SELECT *, JSON_EXTRACT(filter_apps, JSON_UNQUOTE(JSON_SEARCH(filter_apps, 'all', 'c130b917983c719495042e31306ffb'))) AS hit
FROM campaigns
) AS t
JOIN (SELECT @N := @N +1 AS n FROM campaigns, (SELECT @N:=0) dum LIMIT 10) numbers
ON CHAR_LENGTH(filter_apps) - CHAR_LENGTH(REPLACE(filter_apps, ',', '')) >= n - 1
WHERE hit IS NOT NULL;
# for the "JOIN-FROM" use a table that has more or equal entries than the length of your longest JSON array
# make sure the "JOIN-LIMIT" is higher or equal than the length of your longest JSON array
查询说明: