开发者

Join the result of 2 ordered queries without losing the order (in sql)

开发者 https://www.devze.com 2023-02-23 06:06 出处:网络
I have 2 queries, I need to have a query that outputs the result of query 1 and appends the result of query 2 after it:

I have 2 queries, I need to have a query that outputs the result of query 1 and appends the result of query 2 after it:

query 1

SELECT *
FROM events
WHERE START >= '2010-1-1'
ORDER BY START 

query 2:

SELECT *
FROM events
WHERE START &开发者_StackOverflowlt; '2010-1-1'
AND END > '2010-1-1'
ORDER BY END

a result could be:

01 jan 2010 - 02 jan 2010 ->from query 1

02 jan 2010 - 01 feb 2010 ->from query 1

01 nov 2009 - 10 feb 2010 ->from query 2

01 oct 2009 - 11 feb 2010 ->from query 2

In other words, first the events that have not begun on the date yet ordered by start and then the events in progress ordered by end.

I can't seem to use join as that changes the order...


You could add dummy order by columns and UNION the results of both selects to return the results ordered as you like.

SELECT  *
        , 'Start' AS OrderBy1
        , Start AS OrderBy2
FROM    events
WHERE   START >= '2010-1-1'
UNION ALL
SELECT  *
        , 'End' AS OrderBy1
        , End AS OrderBy2
FROM    events
WHERE   START < '2010-1-1'
        AND END > '2010-1-1'
ORDER BY
        OrderBy1 DESC
        , OrderBy2  
0

精彩评论

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