简体   繁体   中英

Query on a list of json in Mysql 5.6

I am using mysql 5.6 and it will not be feasible for me to upgrade it to 5.7. I have a table which stores json as an attribute. Attaching screenshot for reference.

在此,policy_status列包含每个用户的不同策略的状态和值作为json。

Here, the column policy_status contains status and values of different policies as json for each user. How can I find the list of users, say, with appVersion' status as success and value = 1437. I got a few references online but as I am new to stored procedures I am not able to reach a solution. I will appreciate any help. Thanks in advance.

It is not efficient at all but may can help you with ideas:

SELECT *
FROM data
WHERE
  (LOCATE('"employmentType":["status":"success"]', policy_status) > 0
   AND
   LOCATE('"value": 1', policy_status) > 0);

Using the LOCATE function you can see whether the field contains your desired appVersion and value strings. See sqlfiddle demo here.

Where the simple test data :

CREATE TABLE data (
  id INT UNSIGNED NOT NULL,
  policy_status TEXT
);

INSERT INTO data (id, policy_status) VALUES
(1,'{"employmentType":["status":"success"], "value": 1}'),
(2,'{"employmentType":["status":"no"], "value": 1}'),
(3,'{"employmentType":["status":"no"], "value": 0}'),
(4,'{"employmentType":["status":"success"], "value": 0}'),
(5,'{"employmentType":["status":"no"], "value": 1}');

gives the result :

{"employmentType":["status":"success"], "value": 1}

Where both strings are found.

UPDATE :

Also if you can add FULLTEXT index for your policy_status column than you can use fulltext search in the WHERE clause:

...
WHERE
   MATCH (policy_status) AGAINST ('+"employmentType:[status:success]" +"value: 1"' IN BOOLEAN MODE)

Note the + and " characters in AGAINST(...) . They are special boolean full-text search operators. See here .

A leading or trailing plus sign indicates that this word must be present in each row that is returned

and

A phrase that is enclosed within double quote (") characters matches only rows that contain the phrase literally, as it was typed. The full-text engine splits the phrase into words and performs a search in the FULLTEXT index for the words. Nonword characters need not be matched exactly.

If it is not an option in your case, you can use LIKE for matching the substrings:

...
WHERE
  (policy_status LIKE '%"employmentType":["status":"success"]%'
   AND
   policy_status LIKE '%"value": 1%');

See sqlfiddle demo for both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM