Check if an element is contained in the values ​(array) of a json column in MySql

五迷三道 提交于 2021-02-09 07:38:38

问题


I have the following values ​​inside a cell of a json column in MySql:

{
    "produttori": [
        "8",
        "9"
    ],
    "articoli_alternativi": [
        "3",
        "9"
    ],
    "articoli_accessori": [
        "5",
        "6",
        "7",
        "8"
    ],
    "tecnologie": [],
    "fornitori": [
        "9",
        "8"
    ],
    "classificazioni": [
        "3",
        "4"
    ]
}

I would like to make a query that extracts data based on the existence of a value in the array at the fornitori key.
For now I've tried this:

query = 'SELECT nome, formulati_commerciali FROM articolo WHERE JSON_CONTAINS(JSON_EXTRACT(dati, "$.fornitori"), "' + \
        value+'", "$")'

Which print is:

SELECT name, data FROM articolo WHERE JSON_CONTAINS(JSON_EXTRACT(data, "$.fornitori"), "8", "$")

Basically the condition is that value ("8") must be inside the fornitori list, otherwise skips the element.
Unfortunately, the query did not produce any results.
I would like to know how you can formulate such a query in MySql. I will need them often!

Thanks in advance!


回答1:


This should do it:

SELECT name, data 
FROM articolo 
WHERE JSON_CONTAINS(data, '"8"', '$.fornitori')

The double quotes around 8 are important, in order to properly match the JSON data. On the other hand, the query consistently uses single quotes for string literals.




回答2:


You can use

SELECT data
  FROM 
  (
    SELECT  @i := @i + 1 AS rn,
            JSON_UNQUOTE(JSON_EXTRACT(data,CONCAT('$.fornitori[',@i-1,']'))) AS elm,
           data               
      FROM information_schema.tables 
     CROSS JOIN articolo 
     CROSS JOIN (SELECT @i := 0) r
  ) q
 WHERE elm = 8

in order to search for the spesific value within a spesific array("fornitori")

Demo



来源:https://stackoverflow.com/questions/64535158/check-if-an-element-is-contained-in-the-values-array-of-a-json-column-in-mysq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!