简体   繁体   中英

Ordering in mysql based on values of other columns

This might be an XY problem, so I'll try to explain from the start:

A client has an event page on his website and can manage his events in a CMS. He needs to be able to select a start and end date for the event and also wether the start- or end date is leading.

Some events run for around half a year, so lets say june first till december first. These events have to show up in the results, but because they run for such a long time, he doesn't want them to always be the first events you see on the events page, as the event page orders by start date. This is why he can select what date is leading. In case the end date is leading in this example, other events that start after june first, have to show up higher in the list than this event, but when the start date is leading, the event shouldn't be showed at all if the current date is later then june first, but has to show up higher in the list than events that have a later start date or events that have a leading end date.

Does this make sense?

These are the relevant columns I currently have

event_id           (int)
event_name         (varchar)
event_startdate    (int, unix timestamp through PHP)
event_enddate      (int, unix timestamp through PHP)
event_date_leading (int, 1 for enddate, 0 for startdate)

In plain english, I think I'm looking for a query like this, but I cannot translate it to MySQL:

select all events from events_table but dont show the events that have event_date_leading 0 and the startdate is in the past, then, place events that have event_date_leading 0 higher than events that have events_date_leading 1 while their event_startdate is actually earlier

It looks like I need some sort of double sorting in my query, but I don't know wether that is possible.

What I've tried so far is retrieving ALL events, then checking their dates and leading values with PHP and do/don't show them according to that, but that still doesn't let me sort the way I want it to.

Can anyone point me in the right direction?

SELECT * FROM events_table WHERE event_startdate < NOW() AND event_date_loading=0 ORDER BY event_startdate ASC,event_date_leading DESC,event_startdate

This will select all events where the startdate is in the future and event_date_leading is equal to 0. Also it will first order the result in start date ASCending and the Descending to the event_date_leading.

If it's not working, please set up a sqlfiddle and send us the desired results with a sample code you tried.

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