mysqlmaterialized-path-pattern

Materialized path sorting order by date + path


I have database with comments (materialized path)(mysql). If i select all comm`s with "select * from comm where post_id=10 order by path ASC" in result i have comments from post ordered by path with older date on top and newer at bottom.

So, is there a way to select newer on top with like in disqus? if i simply "order by path DESC" - than branch is displayed upside down - it is not what i want. So i need order by date(new comm on top) and path. Thanks.!

link to bigger pic https://drive.google.com/file/d/0BwIgYhO9h960ZTl4a24wNXFFQnM/view?usp=sharing

Bigger pic


Solution

  • You just have to find the part after the first point.

    Then you order DESC until the first part, and ASC after the last part.

    SELECT * FROM comments 
      WHERE post_id=10
      ORDER by substring_index(path, '.', 1) DESC,
          path ASC
    

    Note that you have an error in your attached file in the third column, inverting 9972 and 9974.

    I don't know if, in this case, the MySQL optimization engine uses the index set on path to sort the result. It should be more efficient to add a column to your model.