I am totally new to JSON data type in MySQL. I installed MySQL 5.7.34 a few days ago and now I'm playing around with it.
So, I have following table in MySQL 5.7.34
:
CREATE TABLE tb_products (
product_id int(11) NOT NULL AUTO_INCREMENT,
product_name varchar(255) NOT NULL,
product_attributes json NOT NULL,
PRIMARY KEY (product_id)
);
One of the row in this table looks like as:
product_attributes field:
[
{
"site": "site1",
"categories": [
"site1 cat1",
"site1 cat2",
"site1 cat3"
]
},
{
"site": "site2",
"categories": [
"site2 cat1",
"site2 cat2"
]
}
]
My first question is that have I put above JSON data in proper format for doing various further operations?
Or whether it should have a key attributes
for easy accessing the data:
{
"attributes": [
{
"site": "site1",
"categories": [
"site1 cat1",
"site1 cat2",
"site1 cat3"
]
},
{
"site": "site2",
"categories": [
"site2 cat1",
"site2 cat2"
]
}
]
}
Now, I need to perform below operations but I can't figure out how to do all this:
- How to select row where
site = site1
? - How to select row where
site = site1
andcategories = site1 cat1
? - How to add one another object
{"site": "site3", "categories": [...]
to theproduct_attributes
column? - How to add one another array element
site1 cat4
wheresite = site1
? - How to remove attribute
site = site1
? - How to remove array value from categories
site1 cat1
wheresite = site1
?