Have MySQL return JSON keys which themselves contain certain values

时间:2018-06-19 11:10:09

标签: mysql sql json

The problem I am trying to solve is to have a MySQL query return the Keys within a JSON that has the value "stage":"Functioning". I've been trying to work this problem out for a while now but can't find a solution.

It's worth adding as well that there will be several JSONs within the database table.

One of the JSONs is as follows:

{
  "1493510400":{
    "stage":"Resting",
    "dateAltered":"true"
  },
  "1508716800":{
    "stage":"Functioning",
    "dateAltered":"true"
  },
  "1522713600":{
    "stage":"Functioning",
    "dateAltered":"true",
    "stageAltered":"true"
  },
  "1537315200":{
    "stage":"Functioning",
    "stageAltered":"true"
  },
  "1551916800":{
    "stage":"Resting",
    "stageAltered":"true"
  },
  "1566518400":{
    "stage":"Resting",
    "stageAltered":"true"
  },
  "1581120000":{
    "stage":"Functioning"
  },
  "1595721600":{
    "stage":"Resting"
  }
}

Each level has a timestamp as its key. Within each level, there will always be a value for 'stage'. These are only ever going to be Resting or Functioning. From here, I need to create a query that will return all the keys (timestamps) that have a value "stage":"Functioning".

I've got SELECT JSON_KEYS(field_value) working fine and it returns an array of the timestamps but when I try adding on some WHERE statements, it fails to return anything.

Some of the queries I've tried are:

  • SELECT JSON_KEYS(field_value) WHERE JSON_EXTRACT(field_value, '$*.stage') = 'Functioning'
  • SELECT JSON_KEYS(field_value) WHERE JSON_CONTAINS(field_value, '{"stage":"Functioning"}', '$.stage')

I know I'm probably being an idiot here so apologies if this feels like a waste of time to people but I'm totally stumped right now.

Is what I'm trying to accomplish even possible within MySQL?

My current version of MySQL is 5.7.22

Thanks

1 个答案:

答案 0 :(得分:0)

恐怕您的版本不支持该功能。如果您可以升级到MySQL 8.0.11,则可以使用JSON_TABLEJSON_SEARCH 或类似的方法,具体取决于您的具体情况(老实说,根据您的帖子,您究竟想要实现什么目标并不知道)。 / p>