mysql: how to save ORDER BY after LEFT JOIN without reorder?

前端 未结 4 865
你的背包
你的背包 2021-01-22 22:22

I\'ve two table:

1) profiles

+----+---------+
| id | name    |
+----+---------+
|  1 | WILLIAM |
|  2 | JOHN    |
|  3 | ROBERT  |
|  4 | MI         


        
4条回答
  •  佛祖请我去吃肉
    2021-01-22 22:59

    I know this question is a couple of years old, but I didn't find this possible solution already offered. This is the solution that worked best for me to keep the subquery results in the correct order.

    Consider adding a "row_number" to your subquery. Then use ORDER BY on row_number.

    This explains how to add the row_number: select increment counter in mysql

    In my case, I have an unknown number of possible rows in a hierarchical recursive query that I need to keep the order results of the subquery to remain the same in the outer query.

    This is my query:

    SELECT l.row_number, l.userid, l.child, p.id, p.username
    FROM (
    
        SELECT  @rownum := @rownum + 1 AS row_number, u.parent AS userid, _id  AS child 
                    FROM (
                        SELECT  @r AS _id, (SELECT  @r := parent FROM new_clean WHERE userid = _id) AS parent
                                    FROM (SELECT @r := ?) AS vars, new_clean h
                                    WHERE   @r <> 0 
                        ) u
                    CROSS JOIN (SELECT @rownum := 0) r
                    WHERE u.parent <> 0                     
        ) l 
    
            LEFT JOIN profile p ON p.userid = l.userid
            ORDER BY row_number
    

提交回复
热议问题