简体   繁体   中英

Querying a specific JSON key value from mysql

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.

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 eg "%Cancer%" .

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