I have two tables in mysql schema, let's call them sites
and fields
. The sites table as the following schema:
create table if not exists sites
(
id int auto_increment
primary key,
collection_id int null,
name varchar(255) null,
properties text null,
)
;
And the fields has the following schema
create table fields
(
id int auto_increment
primary key,
collection_id int null,
name varchar(255) null,
code varchar(255) null,
)
;
The two tables can be joined on the collection_id
column. The sites
table stores json data in the properties column with the keys of the json objects being values of id column in field table. For example, here is a sample json that can be found in the properties column
{"1281":"Type A","1277":4}
The keys in the json above are the ids of a record in the fields.
+---------+--------------+--------------+
|id | name | code |
+---------------------------------------+
| 1277 | Years | Yr |
+---------------------------------------+
| 1281 | Type | Ty |
+---------+--------------+--------------+
Now, I want to output properties json where the keys are replaced by the names of the field instead of the id values. Using the above example the output should look like:
{"Type": "Type A", "Years": 4}
I have tried the following so far
select JSON_OBJECT(fd.name, JSON_EXTRACT(st.properties, concat('$."', fd.id, '"'))) as prop
from sites as st join fields as fd on fd.collection_id = st.collection_id where st.collection_id = 145 and
JSON_EXTRACT(st.properties, concat('$."', fd.id, '"')) is not null ;
However, this produces json object for each field instead of site.
It outputs something like below:
+----------------------------+
| prop |
+-----------------------------+
| {"Type": "Type A"} |
| |
+----------------------------+
| {"Type": "Type B"} |
| |
+-----------------------------+
| |
| {"Year": 4} |
| |
+----------------------------+
How can modify the above code to get desired output? Or Is there a better solution?