How can I do where clause containing json in mysql?

4.3k Views Asked by At

For example, I have a column named json in table A

Json column contains json data like this :

record 1 : {"dept_code": "012", "unit_code": "22"}
record 2 : {"dept_code": "013", "unit_code": "23"}
etc

I want to take the data records with json column that contain dept_code = 012

SELECT * FROM table_A WHERE json = ...(looking dept_code = 012)...

How can I do that?

Note :

I tried to find answers on the site stackoverflow, but I did not find it. So I make this question

3

There are 3 best solutions below

1
On BEST ANSWER

Maybe this can help:

SELECT * FROM table_A where json like '%"dept_code": "012"%';
1
On
 ...WHERE JSON_CONTAINS(`json `, '{"dept_code " : "012"}')
2
On

Pretty sure JSON_CONTAINS is what you want. View the docs here

I don't have a sandbox to test this right now, but your example would translate to something like:

select * from table_A
where json_contains(json, '012', '$.dept_code')

Since dept_code is a property of the object stored in the json column.