如何在mysql/mariaDB中对JSON列执行选择
如何在JSON列上应用WHERE子句以对具有两列id Integer attr JSON的表执行SELECT查询。JSON是嵌套的,在过滤条件下,只允许JSON的一个键值对。此键值对可以位于Josn中的任何位置如何在mysql/mariaDB中对JSON列执行选择,mysql,mariadb,mysql-python,Mysql,Mariadb,Mysql Python,如何在JSON列上应用WHERE子句以对具有两列id Integer attr JSON的表执行SELECT查询。JSON是嵌套的,在过滤条件下,只允许JSON的一个键值对。此键值对可以位于Josn中的任何位置 +----+----------------------------------------------------------------- | id | attr
+----+-----------------------------------------------------------------
| 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中,可以使用 例如,如果要从数据库中选择所有甜甜圈,请执行以下操作:
SELECT * FROM t WHERE JSON_CONTAINS(attr, '"donut"', '$.type');
注意:在MariaDB中,JSON函数可用于所有文本数据类型VARCHAR、text等。。该类型只是LONGTEXT的别名。类似于,您可以直接从json by字段中选择,如:
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';
你们能发布一些数据,或者你们尝试过的查询吗?@TimBiegeleisen我应该能够过滤Json列。FYU从attr包含batter2:200MySQL 5.7的表_name中选择id,其中包含一些JSON函数。