I am trying to create a query that will result in a list of images (from image table) and for each image, an array of objects (which are comments that users posted on the image) – from a comment table.
each row in the result should be something like that (encoded in JSON):
{"image_id":"100","name":"dog","comments":[{"userId":"eyal","comment":"nice picture","timestamp":"xxxxxx"},{"userId":"dan","comment":"i like the picture","timestamp":"xxxxxx"}]}
the issue is that i want to sort the comments by timestamp (a field in the comment table), but because i’m doing group by images, i can not sort before group by.
Basically, i need a way to sort the comments table before joining it to the image table.
Thats my query that is not working (all ok beside the sort)
$sql = "select images.id,images.name, CONCAT('[', GROUP_CONCAT(DISTINCT CONCAT('{\"userId\":\"',comm_sorted.uid,'\",\"comment\":\"',comm_sorted.comment,'\",\"timeStamp\":\"',comm_sorted.timestamp,'\"}') separator ','),']') as comments FROM images LEFT JOIN (select * from comments order by timestamp DESC) as comm_sorted on images.id=comm_sorted.id group by images.id order by images.Timestamp DESC, comm_sorted.timestamp DESC LIMIT $offset, $limit";
help will be appreciated
Eyal.
You can put an
ORDER BY comm_sorted.timestampoption in theGROUP_CONCAT()function.