如何在 mysql/mariaDB 中的 JSON 列上执行 SELECT

how to perform a SELECT on a JSON column in mysql/mariaDB

如何在 JSON 列上应用 WHERE 子句以对具有两列(id Integer,attr JSON)的 table 执行 SELECT 查询。 JSON是嵌套的,过滤条件中只允许有一对json的键值对。这个键值对可以在Josn的任何地方。

+----+-----------------------------------------------------------------
| id | attr                                                                                          
|
+----+-----------------------------------------------------------------
|  1 | {"id":"0001","type":"donut","name":"Cake","ppu":0.55}                                         
|
|  2 | {"id":"0002","type":"donut","name":"Cake","ppu":0.55,"batters":
       {"batter1":100,"batter2":200}} 
+----+-----------------------------------------------------------------

在 MariaDB 10.2 中,您可以使用 JSON functions

例如,如果您想要 SELECT 数据库中的所有甜甜圈,您可以:

SELECT * FROM t WHERE JSON_CONTAINS(attr, '"donut"', '$.type');

注意: 在 MariaDB 中,JSON 函数适用于所有文本数据类型(VARCHAR、TEXT 等)。 JSON 类型只是 LONGTEXT.

的别名

类似,您可以 select 直接从 json 按字段,如:

SELECT json_extract(attr, '$.type') FROM t;

如果您仍在使用 MySQL 5.6(没有 JSON 解析支持),我们可以使用 substring_index 函数来解析 json 数据。

这是一个工作示例:

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `attr` longtext COLLATE utf8_unicode_ci NOT NULL,
  `created_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO products (attr, created_at) 
VALUES 
('{"id":"0001","type":"donut","name":"Cake","ppu":0.55}', now()),
('{"id":"0002","type":"donut","name":"Cake","ppu":0.55,"batters":{"batter1":100,"batter2":200}}', now()),
('{"id":"0003","type":"apple","name":"Apple","ppu":0.60}', now()),
('{"id":"0003","type":"orange","name":"Orange","ppu":0.65}', now());

select 
    substring_index(substring_index(attr, '"type":"', -1), '",', 1) AS product_type
from products
having product_type = 'donut';