繁体   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