Memmo
Memmo

Reputation: 268

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

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!

Upvotes: 4

Views: 2367

Answers (2)

Barbaros Özhan
Barbaros Özhan

Reputation: 65218

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

Upvotes: 0

GMB
GMB

Reputation: 222432

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.

Upvotes: 2

Related Questions