0

我正在尝试编写一个SQL 查询,它总是给出三行结果。数据库如下:

uid | program_date | program_time | program_name
------------------------------------------------ 
1   | 2012-04-16   | 21:00        | Some movie
2   | 2012-04-16   | 23:00        | Program end
3   | 2012-04-17   | 10:00        | Animation
4   | 2012-04-17   | 11:00        | Some other movie
5   | 2012-04-17   | 12:00        | Some show

我所需要的 - 总是有三排 - 现在正在播出的节目,下一个节目和即将播出的节目。所以如果今天是2012-04-16 21:00它应该输出Some movie, Program end, Animation.

2012-04-17 00:00它应该输出Program end, Animation, Some other movie.

问题是如果没有记录,我需要在一天内“导航”回来WHERE program_date = date("Y-m-d") AND program_time <= date("H:i:s");

还有另一个问题 - 数据库没有 Unix 时间戳字段,只有Uid, program_date(日期字段)和program_time(时间字段)和program_name.

此外,可能存在Uid未按顺序插入表中的情况,因为某些节目条目可能会插入到现有节目时间表之间。

我正在尝试各种方法,但想在一个 SQL 查询中完成所有事情,而不是在 PHP 中循环。

有人能帮我一下吗?

4

1 回答 1

2

As TV-people count and show time in rather strange manner, MySQL function may be created to handle their non-human ;-) logic easier:

CREATE FUNCTION TV_DATE(d CHAR(10), t CHAR(5))
RETURNS CHAR(16) DETERMINISTIC
RETURN CONCAT(d, IF (t < "06:00", "N", " "), t);

User-defined functions are declared per-database and this may be done just once. DETERMINISTIC tells that function always return the same result for the same input and internal MySQL optimizer may rely on that. N is just a letter which is larger (in string comparison) than whitespace. Consider it as mnemonics for next or night.

note: Hours should be always formatted with 2 digits!

Then using this function we may select what we need even simpler:

-- what is on air now
(SELECT `program_name`, TV_DATE(`program_date`, `program_time`) AS `tv_time`
 FROM `table` 
 WHERE (`tv_time` <= TV_DATE(date("Y-m-d"), date("H:i"))
 ORDER BY `tv_time` DESC 
 LIMIT 1)

  UNION

-- next and upcomming
(SELECT `program_name`, TV_DATE(`program_date`, `program_time`) AS `tv_time`
 FROM `table`
 WHERE (`tv_time` > TV_DATE(date("Y-m-d"), date("H:i"))
 ORDER BY `tv_time` ASC
 LIMIT 0, 2)

Keep in mind, that if all records in DB are in future you'll get only 2 of them. The same for situation, when the next program is the last one in DB.

You may add different constant values into queries in order to distinguish those 2 situations.

于 2012-04-17T19:49:11.123 回答