I have two tables: Files
and FileLogs
and I'm trying to get rid of the FileLogs
table and store some data from it inside the Files
table.
Files
id | lastStatusId | meta |
---|---|---|
187 | 101 | NULL |
188 | 101 | { "foo": "bar" } |
FileLogs
id | fileId | statusId | createdAt | meta |
---|---|---|---|---|
1 | 187 | 101 | 2019-06-18 19:43:19 | NULL |
2 | 187 | 102 | 2019-06-18 19:43:22 | NULL |
3 | 187 | 202 | 2019-06-18 19:45:32 | { "foo2": "bar2" } |
I already added the lastStatusId
column to the Files table (defaults to 101).
To get the latest statusId
for every file from the logs into the latestStatusId
I run this query and it works great:
UPDATE
`Files` f1,
(
SELECT
f.id as fileId,
fl.statusId,
fl.meta
FROM
(
SELECT
MAX(id) as id,
fileId
FROM
`FileLogs`
GROUP BY
fileId
) AS latestIds
LEFT JOIN `FileLogs` AS fl ON latestIds.id = fl.id
LEFT JOIN `Files` AS f ON f.id = fl.fileId
ORDER BY
fl.id ASC
) temp1
SET
f1.lastStatusId = temp1.statusId
WHERE
f1.id = temp1.fileId;
I thought I could use a similar query to go over all FileLogs and write the status into the Files' meta
field like so:
UPDATE
`Files` f1,
(
SELECT
f.id as fileId,
fl.statusId,
fl.meta,
fl.createdAt
FROM
`FileLogs` AS fl
LEFT JOIN `Files` AS f ON f.id = fl.fileId
) temp1
SET
f1.meta = JSON_MERGE_PATCH(
COALESCE(f1.meta, '{}'),
JSON_OBJECT(
'statusInfo',
JSON_OBJECT(
CONCAT('', temp1.`statusId`),
JSON_OBJECT(
'createdAt',
temp1.createdAt
)
)
)
)
WHERE
f1.id = temp1.fileId;
Result of the subquery is something like this:
fileId statusId meta createdAt
187 101 NULL 2019-06-18 19:43:19
187 102 NULL 2019-06-18 19:43:22
187 202 {"foo": "bar"} 2019-06-18 19:43:26
But the SET is only run for the first f1.id = temp1.fileId
and not the second or third (which kind of makes sense) - and the result looks like this:
File id:187
meta
{
"statusInfo": {
"101": {
"createdAt": "2019-06-18 19:43:19.000000"
}
}
}
- How can I achieve that the two other status (102, 202) are also added to the meta column?
- How can I also get the FileLogs' meta data in there as well (if not null)?