簡體   English   中英

SQL Query用於選擇具有開始和結束日期的即將發生的事件

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

我需要顯示來自數據庫的即將發生的事件。 問題是,當我使用查詢時,我正在使用任何已經過去的開始日期的事件將在即將發生的事件列表中顯示較低,而不管它們是否是最新的事實

我的桌子(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

我的查詢(學說):

    $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);

基本上我希望當前正在進行的任何事件(如果今天在start_day和end_day之間)都在列表的頂部。 如果可能的話,我該怎么做呢? 原始的SQL查詢也是很好的答案,因為它們很容易變成DQL。

解決方案基於以下答案之一:

    $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")

你可以使用案例

當前日期在開始日期和結束日期之間添加一個案例,分數為1.所有其他分數為0

然后按分數排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM