开发者

Combining several query results into one table, how is the results order determined?

I am retuning table results for different queries but each table will b开发者_JAVA百科e in the same format and will all be in one final table. If I want the results for query 1 to be listed first and query2 second etc, what is the easiest way to do it?

Does UNION append the table or are is the combination random?


The SQL standard does not guarantee an order unless explicitly called for in an order by clause. In practice, this usually comes back chronologically, but I would not rely on it if the order is important.

Across a union you can control the order like this...

select
   this,
   that
from
   (
   select
      this,
      that
   from
       table1
   union
   select
     this,
     that
   from
     table2
   )
order by
   that,
   this;


UNION appends the second query to the first query, so you have all the first rows first.


You can use:

SELECT Col1, Col2,...
FROM (
    SELECT Col1, Col2,..., 1 AS intUnionOrder
    FROM ...
) AS T1
UNION ALL (
    SELECT Col1, Col2,..., 2 AS intUnionOrder
    FROM ...
) AS T2
ORDER BY intUnionOrder, ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜