My MySQL table looks like this:
_id | _masterid |
---|---|
17 | null |
18 | 17 |
19 | 17 |
20 | null |
21 | null |
22 | 20 |
23 | 17 |
24 | 20 |
25 | 20 |
Is it possible to order it with a single query so we get this results as output?
_id | _masterid |
---|---|
17 | null |
18 | 17 |
19 | 17 |
23 | 17 |
20 | null |
22 | 20 |
24 | 20 |
25 | 20 |
21 | null |
_ids without _masterid are main comments, and _ids with _masterids are replies. So ideally I’d like to order comment and its replies bunched up together, before proceeding to the next comment.
Thanks!
2
Answers
Yes, it is possible:
The
coalesce(_masterid, _id)
part returns either_masterid
if it’s notNULL
, or_id
otherwise. Then you put the parent thread first by placing_masterid
beingNULL
before the non-NULL
ones.I would recommend to fill
parent
(_masterid
) with self value.So whenever you initiate the comment or whatever topic like:
(17, null), (20, null)
you do(17, 17), (20, 20)
.This approach will allow you to do simple order with regular indexes in use:
The approach of Robo Robok is good. But it will have small performance issue because it uses the function result for ordering which is slower than regular indexes.