2016-02-05 66 views
0

我有一个SQL数据库字段,其中包含存储的JSON类型数据。json sql中的单值条件

----------------------------- 
id |  tags    | 
----------------------------- 
1 | ['cat','dog']  | 
2 | ['lion','cat','dog'] | 

我想通过传递where条件作为cat从该表中选择并得到所有的JSON领域。我将如何做到这一点?

+0

使用'Like'运算符。请参阅http://www.w3schools.com/sql/sql_like.asp – Apb

+1

您使用的是哪个版本的MySQL? 5.7对JSON有本地支持。 –

+0

它不可能与SQL查询我认为 –

回答

0

自MySQL 5.7.8起使用JSON_EXTRACT函数。从例如 https://dev.mysql.com/doc/refman/5.7/en/json.html#json-paths

A JSON path expression selects a value within a JSON document. 

Path expressions are useful with functions that extract parts of or modify a JSON document, to specify where within that document to operate. For example, the following query extracts from a JSON document the value of the member with the name key: 

mysql> SELECT JSON_EXTRACT('{"id": 14, "name": "Aztalan"}', '$.name'); 
+---------------------------------------------------------+ 
| JSON_EXTRACT('{"id": 14, "name": "Aztalan"}', '$.name') | 
+---------------------------------------------------------+ 
| "Aztalan"            | 
+---------------------------------------------------------+ 

注意提取他们是直列creatinng一个JSON对象,所以你 :“{‘ID’:14,‘名’:‘Aztalan’}”实际上是你的列值。

+0

但我存储我的JSON只有像上面显示的问题'['猫','狗']' –

0

MySQL中的JSON操作很慢。我建议你使用REGEXP。

// get all rows having "cat" value 
select * from animals_tbl 
where tags regexp 'cat'; 

// get all rows based on multiple filters 
select * from animals_tbl 
where tags regexp 'lion|cat';