1

I have a param field in my mysql table what's contains json data. After encode looks like this:

  'config.enable_comments' => string '1' 
  'metadata.description' => string '' 
  'metadata.keywords' => string '' 
  'metadata.robots' => string '' 
  'metadata.author' => string '' 
  'config.primary_category' => string '157' 

how can i make a mysql query depending for example on config.primary_category.

SELECT params
FROM #__zoo_item
WHERE  config.primary_category = ". $id;
5
  • 4
    thats a bad idea to store it as json. you really should normalize your database. Commented Feb 15, 2012 at 14:05
  • If it isn't too late to change this to a proper normalization scheme, you absolutely should change it. This is going to cause you lots and lots of headaches... Commented Feb 15, 2012 at 14:07
  • the thing is that this one is a joomla component(purchased) what is storing some params as json and I would like to trigger out some items where config.primary.category is equivalent with id. I'm not a professional maybe I'm doing something wrong. Commented Feb 15, 2012 at 14:11
  • Safest thing is to retrieve the json string, json_decode it back to a native PHP structure, and work with that. About all you can inside MySQL is string operations, and you're not VERY careful with those, you'll get garbage for results. Commented Feb 15, 2012 at 14:21
  • oka thanks I'm going to think about another workaround Commented Feb 15, 2012 at 14:26

1 Answer 1

2

And over a year later... I needed to do this kind of query with a project where the database can not be normalized for some reason.

This is one possible solution:

SELECT * 
FROM myTable 
WHERE if(
  instr(myField,'myJsonField'),
  substring(
    substring(myField,instr(myField,'myJsonField')+15),
    1,
    instr(substring(myField,instr(myField,'myJsonField')+15),'\",\"')-1
  ),
  ''
) = 'theJsonValue'

Please note that 'myJsonField' has a length of 11, adding to that the symbols of separation of JSON format is 15.

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

Comments

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.