简体   繁体   中英

How to union two ordered queries in the same table

I have events table with columns 'title', 'description', 'start_date', 'end_date'.

I want to get ordered list live and future events, depends on 'start_date' and 'end_date'.

I try

(
    select * 
    from `events`
    where `start_date` < NOW() and `end_date` > NOW() 
    order by `start_date` desc
) 
union all
(
    select * 
    from `events`
    where `start_date` > NOW() 
    order by `start_date` desc) 

but result have not that ordering which I want. I want at first ordered list by start_date live events after that ordered list by start_date future events.

I think you do not need union in this one. Just put a OR condition in your basic query.

Then, to split the result into "this one is live" and "this one is future" you can use a flag

SELECT *, start_date < NOW() AS flag 
FROM `events`
WHERE (`start_date` < NOW() and `end_date` > NOW()) 
   OR `start_date` > NOW()
ORDER BY flag DESC, start_date

Nota : the DESC is here to show you you want live before future event. Otherwise just put ASC .

Try this:

select * from (
(
    select start_date, end_date, 'Live' as event_type
    from `events`
    where `start_date` < NOW() and `end_date` > NOW() 
) 
union
(
    select start_date, end_date, 'Future' as event_type
    from `events`
    where `start_date` > NOW() ) ) a
ORDER BY event_type desc
, case when event_type = 'Live' then start_date end desc
, case when event_type = 'Future' then start_date end asc;

Why can't you just select all events ordered by start_date ?

select * 
from `events`
where (`start_date` < NOW() AND `end_date` > NOW())
or (`start_date` > NOW())
order by `start_date` desc

Anyway live events will be first, then future events

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM