1

I have a mysql (v5.7.23) table contain a json object like this

[{
    "plant_part": "Leaves, Seed",
    "extract_type": "Ethanol",
    "activity": "Colon Cancer",
    "reference": "6"
  },
  {
    "plant_part": "Leaves, Seed",
    "extract_type": "Ethanol",
    "activity": "Lung Cancer",
    "reference": "6"
  }]

Now i want to get value from only the "activity" key. and this is what I'm trying.

$sql = "select * from table where column like '%".$term."%';

but this will select all value from that column. Is there any way get result from specific key?

I mean something like this?

$sql = "select * from table where column.activity like '%".$term."%';

Thank you.

6
  • Do not try it in SQL. use a json Parser in php Commented Aug 20, 2018 at 7:12
  • 1
    Look at MySQL 's json functions Commented Aug 20, 2018 at 7:13
  • @Strawberry is this introduced in mysql 5.7? Commented Aug 20, 2018 at 7:19
  • @Edwin I'm no more qualified to answer that than you, but a limited set of json functions are available in 5.7 - dev.mysql.com/doc/refman/5.7/en/json-function-reference.html Commented Aug 20, 2018 at 7:26
  • @Strawberry before 5.7 I didn't find any reference about it, so I asked because I thought you may know the answer. Thanks anyway. Commented Aug 20, 2018 at 7:30

1 Answer 1

2

You could use JSON_EXTRACT to find the values of activity and compare them:

$sql = "SELECT * 
        FROM table
        WHERE JSON_EXTRACT(column,  '$[*].activity') LIKE '%".$term."%'";

For your sample data the JSON_EXTRACT will return ["Colon Cancer", "Lung Cancer"] which can then be compared against e.g. "%Cancer%".

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.