我在 MySQL 中有一个表,其中有一列存储 JSON 对象。 如何轻松运行可以在 WHERE 子句中包含某些 JSON 字段的查询?
前:
使用名为 articles
+----+---------+--------------------------------------------------------------------------------------------------+
| id | user_id | json_data |
+----+---------+--------------------------------------------------------------------------------------------------+
| 1 | 1 | {"url":"https://www.cpubenchmark.net/","title": "CPU Benchmarks"} |
| 2 | 1 | {"url":"http://www.ebay.com/sch/CPUs-Processors-/164/i.html","title": "Computer and Processors"} |
| 3 | 2 | {"url":"https://www.youtube.com/watch?v=tntOCGkgt98","title": "Funny Cats Compilation" |
+----+---------+--------------------------------------------------------------------------------------------------+
我希望能够写出类似的东西:
SELECT user_id, json_data FROM articles WHERE json_data.title LIKE "%CPU%"
这应该只返回第一行。
最佳答案
您可以使用 json_extract
(5.7 以上)。
https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html#function_json-extract
SELECT user_id, json_data
FROM articles
WHERE json_extract(json_data, '$.title') LIKE '%CPU%';
https://stackoverflow.com/questions/29137915/