apply “ORDER BY” on a “UNION” (Mysql)

后端 未结 4 857
抹茶落季
抹茶落季 2021-01-01 21:35

Good Day. So, everythign is in the title :)

I am looking to merge the result of two requests and order the result together (as in not one after the other). => I was

4条回答
  •  失恋的感觉
    2021-01-01 21:59

    SELECT *
    FROM (
    (SELECT * FROM user_relation WHERE from_user_id = 1)
    UNION
    (SELECT * FROM user_relation WHERE to_user_id = 1)
    ) AS i
    ORDER BY trust_degree
    

    You have to assign an alias to your select. But in this case a UNION is not necessary and could be replaced by a simple OR, as @Karoly Horvath points out in his comment. The resulting query would look like this:

    SELECT 
     * 
    FROM user_relation 
    WHERE from_user_id = 1 OR to_user_id = 1 
    ORDER BY trust_degree
    

提交回复
热议问题