1

I have a json object in my database table field like following :

[{"user_id":"xyz","viewed":"false","answered":"false","denied":"false"}]. the other fields are id, q_id and stuff.

I want to search for the user xyz in the table!how can i do that using mysql?

3
  • search for the user could you please elaborate a bit on it ? Commented Nov 25, 2014 at 7:25
  • i want to search for xyz in the above object! How can i accomplish that? Commented Nov 25, 2014 at 7:26
  • still did not get.. so your input value will be xyz and you want to see if its there in the object which is stored in database ? Commented Nov 25, 2014 at 7:30

4 Answers 4

1

JSON Parsing in MySQL Using Common_schema

Try following query using common schema

select * from tablename where common_schema.extract_json_value(tablename.columnName,'/user_id') = 'xyz';

Reference: http://mechanics.flite.com/blog/2013/04/08/json-parsing-in-mysql-using-common-schema/

Sign up to request clarification or add additional context in comments.

Comments

1

If the object pattern is same across then you can use the substring_index function to parse the data, below is the example of finding the user_id from this pattern

mysql> select replace(substring_index(substring_index('[{"user_id":"xyz","viewed":"false","answered":"false","denied":"false"}]','"user_id":',-1),',',1),'"','') as user_id;
+---------+
| user_id |
+---------+
| xyz     |
+---------+

Now if you want to select all the rows having user_id = xyz you can use the above as

select * from table_name 
where replace(substring_index(substring_index('[{"user_id":"xyz","viewed":"false","answered":"false","denied":"false"}]','"user_id":',-1),',',1),'"','') = 'xyz';

3 Comments

Thanks for this, helped reduce query times by 400ms on a ~10k row table! much more efficient than using LIKE as the (self answered) "Correct" answer does!
It could reduce the time, however thats not an efficient way of storing the user_id like this as a flat JSON, rather the application level should parse the user_id before storing into the DB and then by using the column index it could be far far bettter.
100% agree, but working with a database tied into a black box system here, unfortunately, these things have to be done!
1

thank you for your answers. But i just used a like query and it worked

SELECT viewers from tablename where viewers like '%\"user_id\":\"xyz\"%' && qid= 1;

Comments

0

In mysql there is a functionality for dba called common schema. It has json functionality. Or use find_in_set() function to find coma seperated values in json.

1 Comment

SELECT IF(FIND_IN_SET('"viewed":"false"','[{"user_id":"xyz","viewed":"false","answered":"false","denied":"false"}]'),1,0) AS z

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.