Mysql – Using Regex in WHERE Clause in Mysql 5.7

jsonMySQLmysql-5.7regex

I need a regular expression which will give me only those records which match a pattern.Below is table structure

auto_id (Auto-increment)  | json_string (Text)

Sample records are:

auto_id | json_string 
--------+-----------------------------------------------------------------------------------------------
      1 | {"12":"1774","13":"V.","14":"2","16":"9","17":"39","18":"59","19":"88","20":"144","21":"236"}
      2 | {"12":"1774","13":"Y.","14":"2","16":"7","17":"39","18":"59","19":"88","20":"144","21":"236"}
      3 | {"12":"1774","13":"V.","14":"2","16":"9","17":"39","18":"59","19":"88","20":"144","21":"236"} 

My Query is :

SELECT * 
FROM tbl_json 
WHERE json_data REGEXP '"14":"[1|2]"' 
AND json_data REGEXP '"16":["39|7"]' 
LIMIT 3;

This should return only record with id 2. And not 1 and 3 as "16":"39' or "16":"7" is not part of the json_string.

Does anybody have any ideas what I am doing wrong?

Best Answer

You have mixed the REGEXP syntax for alternatives (first|second) and for symbol classes [abcd]. Your query should look like that:

SELECT * 
  FROM tbl_json 
 WHERE json_data REGEXP '"14":"(1|2)"' 
   AND json_data REGEXP '"16":"(39|7)"' 
 LIMIT 3;