2

I want to retrieve all rows from a table in MySQL table where there is a JSON column called items with content like this:

[{"code":"MH005","qte":1,"totalpriceItem":"28.00"},{"code":"MH027","qte":1,"totalpriceItem":"28.00"}]
[{"code":"MH027","qte":1,"totalpriceItem":"30.00"}]
[{"code":"MH024","qte":1,"totalpriceItem":"28.00"},{"code":"MH028","qte":1,"totalpriceItem":"28.00"},{"code":"MH027","qte":1,"totalpriceItem":"28.00"}]
[{"code":"MH028","qte":1,"totalpriceItem":"30.00"}]

Now i want to be able to select all the row where the key code has the value MH027.

I've tried this but without success:

SELECT *
FROM `transactions`
WHERE JSON_CONTAINS(`item`, 'MH027', '$[*].code')

Any help is much appreciated.

2
  • What version of MySQL are you using? And what exactly do you mean by Items.Row1, Items.Row2 etc Commented Oct 27, 2021 at 14:04
  • Mysql version : mysql 8.0.18 & mariaDB 10.4.10 it mean the content of JSON field in each row inserted in the table Commented Oct 27, 2021 at 14:08

1 Answer 1

2

If I understand correctly you need to use JSON_CONTAINS as follows:

SELECT *
FROM transactions
WHERE JSON_CONTAINS(item, '{"code": "MH027"}', '$')

The second parameter must be valid JSON. You could use JSON_OBJECT('code', 'MH028') if the value is dynamic or could contain special characters.

Sign up to request clarification or add additional context in comments.

3 Comments

Hey sorry to bother again i know this is an answered question but i just want to know how can i tweak it so i can select all the transactions that they had item start with "MH%"
That would be a different question. I would use JSON_TABLE.
can you point me please ?

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.