I have a table of comments (to some article like this):
---------------------------------------------------------------
id |comment_id |likes_count |add_time
---------------------------------------------------------------
0 NULL 0 time0
1 NULL 2 time1
2 0 0 time2
3 0 0 time3
4 NULL 1 time4
5 1 0 time5
The comment_id
is referencing to the id
in the same table. When comment_id
is NULL, this means that this comment is parent (it is not a response to another comment, but rather to the article itself), but if it is not null, it means that this comment is a child (it is a response to another comment in the article).
The query I am using orders the results in a manner where each child is displayed under its parent.
SELECT *
FROM comments
ORDER BY
COALESCE (comment_id, id) DESC,
(comment_id IS NULL) DESC,
likes_count DESC
But I can't figure out how to make parent comments (with their children following it) with the most likes_count
appear first in the results, the likes_count DESC
seems to have no effect, as results are always ordered by the id
.
Result returned by the query:
---------------------------------------------------------------
id |comment_id |likes_count |add_time
---------------------------------------------------------------
0 NULL 0 time0
2 0 0 time2
3 0 0 time3
1 NULL 2 time1
5 1 0 time5
4 NULL 1 time4
Expected result:
---------------------------------------------------------------
id |comment_id |likes_count |add_time
---------------------------------------------------------------
1 NULL 2 time1
5 1 0 time5
4 NULL 1 time4
0 NULL 0 time0
2 0 0 time2
3 0 0 time3
phpMyAdmin show the following info:
Server type: MariaDB
Server version: 10.1.40-MariaDB-cll-lve - MariaDB
Server Protocol version: 10
cpsrvd 11.78.0.34
Database client version:libmysql - 5.1.73
PHP version: 7.2.7
phpMyAdmin: 4.8.3