I have a table called "Student_fees_deposit" and in this table, a column has multiple values in it.
An example is
Student_fees_deposit
id | amount_detail
---|----------------
1 |{"1"{"amount":"5000.00","date":"2022-12-15","amount_discount":"5000.00"}}
2 | {"1":{"amount":"9000.00","date":"2022-12-15","amount_discount":"5000.00"}}
How can I get the amount value for id = 1 which is 5000.00?
4
Answers
Does this answer your question?
In reality, you aren’t supposed to store
JSON
in your database. I’d rather put 3 individual columns (amount
,date
,amount_discount
) instead of storingJSON
, just because of how difficult it is to run complex queries onJSON
data, plus it tends to break rules of normalization.You can easily restructure your table and make it more maintainable, more structure and overall objectively better by just splitting up the
JSON
into individual columns.Another thing you should avoid in the future is storing
Arrays
in your database as that can be easily implemented with1:M
relation which also sort of enforces normalization rule number 3.Here is a working test I tried on my own database:
You can use
substring_index()
:There’s a typo in your first entry, missing ":"
That data type is JSON.
MariaDB supported JSON since 10.2.7 and there are a lot of functions available to use.
MySQL supported JSON since 5.7.8 (their document) and there are a lot of functions available to use.
There are some difference between them – for example: MariaDB do not support column path operator (
->
,->>
). So, you can only use this on MySQL.You can use this SQL statement to get value.
The difference between
JSON_VALUE()
andJSON_EXTRACT()
is theJSON_EXTRACT()
contain double quote and square brackets ([".."]
) in the result. (Tested with MariaDB)Result (MariaDB):
Result:
Sample code in PHP.