3

我将如何编写使用今天的日期并计算任务状态的 SQL 语句。

我认为这应该返回:

1 = complete task (status = completed)
2 = pending task (in the future and not status=completed) 
3 = overdue task (in the past and set to pending)

表 SQL:

CREATE TABLE IF NOT EXISTS `tasks` (
  `task_id` int(10) NOT NULL AUTO_INCREMENT,
  `task_date` date DEFAULT NULL,
  `task_status` enum('pending','approved','complete','cancelled') NOT NULL
  PRIMARY KEY (`task_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
4

3 回答 3

1

如果这只是关于使用动态计算的'overdue'状态扩展预定义的状态集,那么只有一个条件的 CASE 表达式就足够了:

SELECT
  ...
  CASE
    WHEN task_status = 'pending' AND task_date > CURDATE()
    THEN 'overdue'
    ELSE task_status
  END AS task_status,
  ...
FROM tasks
WHERE
  ...
于 2012-09-20T20:03:10.937 回答
0

这些行中的一些东西:

SELECT 
    CASE 
        WHEN task_status = 'complete' THEN 'Complete Task'
        WHEN status != 'complete' AND task_date > NOW() THEN 'Pending Task'
        WHEN status = 'pending' AND task_date < NOW() THEN 'Overdue Task'
FROM 
    tasks

NOW()如果需要,需要用 MySQL 等效替换。

于 2012-09-20T18:25:43.340 回答
0

我会使用以下内容:

SELECT task_id, task_date, 
  CASE 
    WHEN task_status = 'complete' THEN 'completed task'
    WHEN task_status != 'complete' AND task_date > CURDATE() THEN 'pending task'
    WHEN 
      (task_status != 'complete' AND task_date <= CURDATE()) 
      OR (task_status = 'pending') THEN 'pending task'
  END AS task_status_str
FROM 
  tasks
于 2012-09-20T18:35:33.827 回答