如何在MySQL中编写可以解析列中JSON数据的查询?

时间:2015-03-19 05:39:48

标签: mysql json

我在MySQL中有一个表,它有一个存储JSON对象的列。 如何轻松运行WHERE子句中可能包含某些JSON字段的查询?

EX:   使用名为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%"

那应该只返回第一行。

3 个答案:

答案 0 :(得分:8)

您可以使用json_extracthttps://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%';

答案 1 :(得分:5)

我最终以这种方式解决:https://github.com/ChrisCinelli/mysql_json使用UDF。我详细介绍了如何编译它并在README中安装它。它适用于我Ubuntu 12.04.5 gcc version 4.6.3 MySQL 5.5

您将能够运行:

SELECT json_get('{"a":1}', 'a')       => 1
SELECT json_get('{"a":1}', 'b')       => NULL
SELECT json_get('[1,2,3]', 2)         => 3
SELECT json_get('{"a":[2]}', 'a', 0)  => 2

#Also:

SELECT json_get('{"a":{"b":2}}', 'a') => object
SELECT json_get('{"a":[1,2,3]}', 'a') => array

# Verify if it is a valid JSON:

SELECT ISNULL(json_get('{"a":1}'));   => 0  # Valid
SELECT ISNULL(json_get('{"a":1'));    => 1  # Invalid

# Create an example table:

CREATE TABLE `message` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data` text,
  PRIMARY KEY (`id`)
);
INSERT INTO message (id,data) VALUES(1,'{"from":"chris","title":"Awesome Article","body":"Lorem ipsum dolor sit amet, consectetur adipiscing elit."}');
INSERT INTO message (id,data) VALUES(2,'{"from":"loren","title":"Another Article","body":"Lorem ipsum dolor sit amet, consectetur adipiscing elit."}');
INSERT INTO message (id,data) VALUES(3,'{"from":"jason","title":"How to run a query","body":"Lorem ipsum dolor sit amet, consectetur adipiscing elit."}');

# Run queries on JSON values:

SELECT json_get(data,'title') FROM message WHERE id=2;
SELECT id,data FROM message WHERE json_get(data,'from')='chris';
SELECT id,data FROM message WHERE json_get(data,'title') LIKE '%Article%';

答案 2 :(得分:2)

尝试以下查询,看看它是否符合您的需求:

SELECT user_id, json_data
FROM articles
WHERE common_schema.extract_json_value(json_data,'title')
LIKE "%CPU%"

这仅适用于MySQL版本5.1或更新版本。