-6

我有一个看起来像这样的数据库:

编号 | 标题 | 时间戳
-------------------------------------------------- ------------
0 测试 1 2013-02-26 00:00:00
1 测试 2 2013-02-26 00:00:00
2 测试 3 2013-02-29 00:00:00
3 测试 4 2013-03-31 00:00:00

我想选择它们并将它们按如下分组输出:

明天
测试 1
测试 2

本星期
测试 3

超越
测试 4

我需要 MySQL 和 PHP 来输出它,我想不通。

4

2 回答 2

3

您可以使用带有and函数的CASE表达式:Week()Day()

select title,
  case 
    when week(timestamp) = week(curdate())
      then 
        case 
          when day(timestamp) = day(curdate()) +1
          then 'Tomorrow'
          else 'This Week'
        end 
    when week(timestamp) > week(curdate())
      then 'And Beyond'
  end as Col
from yourtable

请参阅SQL Fiddle with Demo

或者这可以写成:

select title,
  case 
    when week(timestamp) = week(curdate())
        and day(timestamp) = day(curdate()) +1
      then 'Tomorrow'
    when week(timestamp) = week(curdate())
      then 'This Week'
    else 'And Beyond'
  end as Col
from yourtable

请参阅带有演示的 SQL Fiddle

这将返回:

|  TITLE |        COL |
-----------------------
| Test 1 |   Tomorrow |
| Test 2 |   Tomorrow |
| Test 3 |  This Week |
| Test 4 | And Beyond |
于 2013-02-25T18:49:44.267 回答
1

您可能需要在 select 子句中使用 case 语句来创建一个计算字段,然后您可以将其分组。

SELECT `id`, `title`, `timestamp`,
    (CASE
        WHEN timestamp < DATEADD(NOW(), INTERVAL 1 DAY THEN 'Tomorrow'
        ELSE WHEN timestamp < DATEADD(NOW(), INTERVAL 1 WEEK THEN 'This week'
        ELSE 'Beyond'
    END) AS `timeframe`
FROM table
ORDER BY `timestamp` ASC

请注意,我正在利用时间戳的排序顺序,这将为您创建一个逻辑分组。

于 2013-02-25T18:54:24.047 回答