Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query a JSON column with an array of object in MySQL

I have a json column with the follow array:

[   {     "id": "24276e4b-de81-4c2c-84e7-eed9c3582a31",     "key": "id",     "type": "input",   },   {     "id": "e0ca5aa1-359f-4460-80ad-70445be49644",     "key": "name",     "type": "textarea",     } ] 

I tried the follow query to get the row that has the id 24276e4b-de81-4c2c-84e7-eed9c3582a31 in the document column, but it returns not results:

select * from jobs WHERE document->'$[*].id' = "24276e4b-de81-4c2c-84e7-eed9c3582a31" 

Anyone know how to do the right query?

like image 946
Fabrício Avatar asked Aug 05 '16 20:08

Fabrício


People also ask

How do I query a JSON column in MySQL?

MySQL provides two operators ( -> and ->> ) to extract data from JSON columns. ->> will get the string value while -> will fetch value without quotes. As you can see ->> returns output as quoted strings, while -> returns values as they are. You can also use these operators in WHERE clause as shown below.

How do I index a JSON column in MySQL?

In MySQL, the only way to index a JSON path expression is to add a virtual column that mirrors the path expression in question and build an index on the virtual column. As you can see, the title column is mapped to the $. title path expression on the properties JSON column.

How do I query an array in MySQL?

Following is an elementary syntax structure to code for MySQL WHERE IN Array command in MySQL server to fetch information using array values and WHERE IN clause: SELECT ColumnName1, ColumnName2, …., ColumnNameNFROM TableNameWHERE ColumnName1 IN(ColumnName1_Value1, ColumnName1_Value2, ColumnName1_Value3);


1 Answers

I use mysql 5.7 and so JSON_CONTAINS can be easily used like this:

SELECT JSON_CONTAINS(                 '[{"id": "24av","name": "she"},{"id": "e0c2", "name": "another_she"}]',                  JSON_OBJECT('id', "e0c2")                 ); 
like image 168
Dina Avatar answered Sep 21 '22 21:09

Dina