0

I want to display specified key_name and key_value of a field with mysql where record is encoded json format

id_user           dtl_master              date    
  1         {"el1":"2","el2":"3"}       2015/01/01
  2         {"el1":"2","el2":"3"}       2015/01/01 
  3         {"el1":"5","el2":"6"}       2015/01/01

My query to filter select is

SELECT id_user,dtl_master FROM tb_inputdata WHERE dtl_master REGEXP '"el2":"([^"]*)4([^"]*)"';

but it return :

 id_user           dtl_master            
      1         {"el1":"6","el2":"4"}          

I wanted to display like this

 id_user              el2            
   1                   4     

I know REGEXP not running on SELECT, but only on WHERE, anybody know how to SELECT only related key_name or key_value?

Thank You

4
  • well a have a ton of data, I should save each pair variable and value on same field, so json format is the solution right now Commented Jan 16, 2015 at 19:26
  • 1
    If your application manually encodes stuff and just throws it in the database, then your application logic itself also has to take care with unfolding it again. Commented Jan 16, 2015 at 19:27
  • 1
    Bad design, however just json_decode and use el2 when fetching the rows from the result. Commented Jan 16, 2015 at 19:31
  • Hi, I don't want display and parse it in application (php) for somereason (memory and efficiency), I tried to do this on mysql first Commented Jan 16, 2015 at 19:31

1 Answer 1

1

I'd recommend going to NoSQL but one way you can extract it is by doing:

SELECT id_user, common_schema.extract_json_value(dtl_master,'/el2') AS el2 WHERE dtl_master REGEXP '"el2":"([^"]*)4([^"]*)"';

If you plan to get common_schema. Installation documentation here.

But of course you can always select using regex, by SELECTing a PREG_REPLACE() value. This isn't default in MySQL alone either; you'd need to get something like this.

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

6 Comments

Is common_schema default to MySQL, or is that something you have to add?
@mopo922 It's something you have to add. If he's going to work with JSON's, he might as well.
thank you for answering,but it require additional stuff to be installed code.google.com/p/common-schema also extract_json_value() is CPU intensive according to documentation. I still waiting for another answer
Can you add instructions to get common_schema to your answer?
@ReidsMekeMeke Best answer you'll receive is switch to NoSQL. Although I'm waiting as well.
|

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.