mysql json 字段作为where查询条件

mysql5.7以上支持json的操作,以及增加了json存储类型
一般数据库存储json类型的数据会用json类型或者text类型

注意:用json类型的话
1)JSON列存储的必须是JSON格式数据,否则会报错。
2)JSON数据类型是没有默认值的。

查询根据表字段的json内容进行查询

  1. 首先创建表
create table log(
     id int not null,
	 content varchar(255),
	 createTime TIMESTAMP,
	 data text
)
  1. 插入几个测试数据
    在这里插入图片描述
  2. 执行查询sql

使用 字段->’$.json属性’进行查询条件

select  * from log where data->'$.id' = 142;

 select data->'$.id' id,data->'$.name' name from log where data->'$.id' = 142;

在这里插入图片描述

测试根据json数组的字段查询
1.再建一个表log2,插入几条json数组数据

[{
		"id": "141",
		"name": "xxx",
		"type": "input"
	},
	  {
		  "id": "142",
		  "name": "xin",
		  "type": "textarea"
	  }
]

在这里插入图片描述
查询json数组里面对象的id等于142的记录

用JSON_CONTAINS(字段,JSON_OBJECT(‘json属性’, “内容”))

select * from log2 where JSON_CONTAINS(data,JSON_OBJECT('id', "142"))

在这里插入图片描述

 搬运自:https://www.codetd.com/article/7994664

原文地址:https://www.cnblogs.com/jinshao/p/15498843.html