在我的页面中,我根据用户选择联系的所选时间范围显示一些条目,并将其保存到mySQL中。
我有4个范围组(我们的工作时间09:00-17:00),用户可以从中选择
09:00 - 11:00
11:00 - 13:00
13:00 - 15:00
15:00 - 17:00
现在,我按以下方式显示结果,按所选时间
排序$sql = "SELECT * FROM table order by chosenTime asc";
我想要做的是根据当前时间对结果进行排序。
例如,如果时间是10:30,则首先显示所选时间在09:00-11:00之间的行。如果是11:00,则首先显示11:00 - 13:00结果。
我正在考虑介于两者之间,但我不知道如何继续这样做。
- 到目前为止我做了什么 -
我的“脏”尝试就是这个。由于格式很难比较这些数据,我创建了一个像
这样的时间 $current = date("Hi", strtotime('+3 hours'));
所以这给了我 1330
在此之后
if ($current < "1059") {
show the results in the default way, chosenTime asc
} else
if (($current >"1100") && ($current < "1259")) {
show the results starting with the ones that chosenTime="11:00 - 13:00" and then
continue to the 13-15, 15-17, 09-11
} else
if (($current >"1300") && ($current < "1459")) {
this follows the above example starting with chosenTime="13:00 - 15:00"
} else
if (($current >"1500") && ($current < "1659")) {
this follows the above example starting with chosenTime="15:00 - 17:00"
}
问题是如何构建该查询?
答案 0 :(得分:1)
使用case when
order by
上的$current
子句并确定排序顺序列。
SELECT * FROM table
order by
case when '$current' < 1100 then 0 -- default order
when '$current' between 1100 and 1300 then 1 -- 09:00 - 11:00
when '$current' between 1301 and 1500 then 2 -- 11:00 - 13:00
when '$current' between 1501 and 1700 then 3 -- 13:00 - 15:00
when '$current' between 1701 and 1900 then 4 -- 15:00 - 17:00
end