I'm trying to query data from multiple tables using JOIN function and i use subquery also. Everything is working fine except for the comments table. I use JSON_ARRAYAGG and inside i uses JSON_OBJ to group them. I want it to be displayed in a manner that the latest comment is on the top. I tried using ORDER BY on the condition but it does not work. I also understand that i can use ORDER BY inside JSON_ARRAYAGG but no luck. Here is the query for comments
(SELECT JSON_ARRAYAGG
(JSON_OBJECT('commentID', c.comment_id,
'username', cu.username,
'body', c.body,
'date_posted', c.created_at) ORDER BY c.created_at DESC)
FROM post_comments c LEFT JOIN user_profile cu
ON c.user_id = cu.user_id
WHERE c.post_id = p.post_id
) AS comments FROM user_posts p INNER JOIN user_profile u ON p.user_id = u.user_id
This query gives me syntax error mainly because of ORDER BY but as far as i know ORDER BY can be used inside JSON_ARRAYAGG. I believe i have something i still didn't figure out. I tried looking here and almost most them tried recommending GROUP CONCAT but as much as i can i don't want to use CONCAT if there would be any other solution.
ORDER BYwithinJSON_ARRAYAGG()in MySQL. This feature was added to MariaDB, but MariaDB is a different database product, not compatible with MySQL. This feature was requested for MySQL in 2019, but so far it has not been implemented.