0

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.

1
  • You can't use ORDER BY within JSON_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. Commented Jun 10 at 3:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.