我如何编写一个使用今天日期并计算任务状态的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;
答案 0 :(得分: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
...
答案 1 :(得分: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代替。
答案 2 :(得分: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