简体   繁体   中英

SQL Query to select upcoming events with a start and end date

I need to display upcoming events from a database. The problem is when I use the query I'm currently using any events with a start day that has passed will show up lower on the list of upcoming events regardless of the fact that they are current

My table (yaml):

  columns:
    title:
      type: string(255)
      notnull: true
      default: Untitled Event
    start_time:
      type: time
    end_time:
      type: time
    start_day:
      type: date
      notnull: true
    end_day:
      type: date
    description:
      type: string(500)
      default: This event has no description
    category_id: integer

My query (doctrine):

    $results = Doctrine_Query::create()
        ->from("sfEventItem e, e.Category c")
        ->select("e.title, e.start_day, e.description, e.category_id, e.slug")
        ->addSelect("c.title, c.slug")
        ->orderBy("e.start_day, e.start_time, e.title")
        ->limit(5)
        ->execute(array(), Doctrine_Core::HYDRATE_ARRAY);

Basically I'd like any events that is currently going on (so if today is in between start_day and end_day) to be at the top of the list. How would I go about doing this if it's even possible? Raw sql queries are good answers too because they're pretty easy to turn into DQL.

SOLUTION Based on one of the below answers:

    $results = Doctrine_Query::create()
        ->from("sfEventItem e, e.Category c")
        ->select("e.title, e.start_day, e.description, e.category_id, e.slug")
        ->addSelect("c.title, c.slug")
        ->addSelect("IF(NOW() BETWEEN e.start_day AND e.end_day,0,1) as score")
        ->orderBy("score, e.start_day, e.start_time, e.title")
        ->limit(5)
        ->execute(array(), Doctrine_Core::HYDRATE_ARRAY);

这应该做:

->orderBy("IF(NOW() BETWEEN e.start_day AND e.end_day,0,1) , e.start_day, e.start_time, e.title")

You can use case .

Add a case when current date is between start and end date, with score 1. All the others with score 0

And then order by score.

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