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

后端 未结 4 786
抹茶落季
抹茶落季 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:50

    To expand on my comment:

    SELECT * into #tempTable FROM (
       SELECT * FROM user_relation WHERE from_user_id = 1
       UNION
       SELECT * FROM user_relation WHERE to_user_id = 1
    )
    as x
    
    SELECT * FROM #tempTable ORDER BY trust_degree
    DROP TABLE #temptable
    
    0 讨论(0)
  • 2021-01-01 21:53
    SELECT a FROM t1 WHERE a=10 AND B=1
    UNION
    SELECT a FROM t2 WHERE a=11 AND B=2
    ORDER BY 1 LIMIT 10;
    

    if you need sort by more fields just add the number of the field, ORDER BY 1, 2, 3 LIMIT 10;

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-01 22:11

    It is written in the documentation of UNION:

    To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT:

    (SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
    UNION
    (SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
    

    ...

    Use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows.

    ...

    To use an ORDER BY or LIMIT clause to sort or limit the entire UNION result, parenthesize the individual SELECT statements and place the ORDER BY or LIMIT after the last one. The following example uses both clauses:

    (SELECT a FROM t1 WHERE a=10 AND B=1)
    UNION
    (SELECT a FROM t2 WHERE a=11 AND B=2)
    ORDER BY a LIMIT 10;
    

    A statement without parentheses is equivalent to one parenthesized as just shown.

    By applying the above information to your query it becomes:

    (SELECT * FROM user_relation WHERE from_user_id = 1)
    UNION
    (SELECT * FROM user_relation WHERE to_user_id = 1)
    ORDER BY trust_degree
    
    0 讨论(0)
提交回复
热议问题