带有datetime的mysql if语句

时间:2013-01-23 06:44:03

标签: mysql

我想在datetime中选择日期,但是如果startDate的时间超过endDate的时间,那么将一天添加到endDate,这是我的代码,但它不起作用,谢谢

SELECT Schedules.*
FROM 'schedules' AS Schedules 
WHERE Schedules.active=1
AND '2013-01-21' BETWEEN DATE(Schedules.startDate) AND 
(
IF TIME(Schedules.startDate)>TIME(Schedules.endDate) THEN 
SELECT (DATE(DATE_ADD(SELECT Schedules.endDate, INTERVAL 1 DAY)))
ELSE SELECT Schedules.endDate
)

2 个答案:

答案 0 :(得分:1)

我为mysql语句创建了一个示例。关注http://sqlfiddle.com/#!8/0752c/6

以及代码(如果需要):

CREATE TABLE `yourtable` (
  `Id` tinyint(4) NOT NULL,
  `Name` char(16) COLLATE utf8_bin DEFAULT NULL,
  `StartDate` DATETIME NOT NULL,
  `EndDate` DATETIME NOT NULL,
  PRIMARY KEY (`Id`)
);

INSERT INTO `yourtable`(`Id`,`Name`,`StartDate`,`EndDate`)
VALUES
(1, 'S1', '2013-01-03 11:23:59', '2013-01-04 13:26:12'),
(2, 'S2', '2013-01-04 00:00:00', '2013-01-04 23:59:59'),
(3, 'S3', '2013-01-12 23:59:59', '2013-01-12 22:20:25'),
(4, 'S4', '2013-01-15 18:15:15', '2013-01-17 13:20:20'),
(5, 'S5', '2013-01-20 21:23:59', '2013-01-22 19:26:12'),
(6, 'S6', '2013-01-04 11:23:59', '2013-01-20 19:26:12'),
(7, 'S7', '2013-01-04 11:23:59', '2013-01-20 08:26:12');


SELECT 
  Id, Name, StartDate, EndDate, 
  CASE WHEN TIME(StartDate) > TIME(EndDate) THEN 'true' ELSE 'false' END AS TF,
  CASE WHEN TIME(StartDate) > TIME(EndDate) THEN DATE(DATE_ADD(EndDate, INTERVAL 1 DAY)) ELSE DATE(EndDate) END AS EndDateUp
FROM yourtable 
WHERE 
DATE('2013-01-04') BETWEEN DATE(StartDate) AND 
  CASE WHEN TIME(StartDate) > TIME(EndDate) 
  THEN DATE(DATE_ADD(EndDate, INTERVAL 1 DAY)) 
  ELSE DATE(EndDate)  END
;

答案 1 :(得分:0)

MySQL没有IF语句,只有IF函数。而不是

IF TIME(Schedules.startDate)>TIME(Schedules.endDate) THEN 
SELECT (DATE(DATE_ADD(SELECT Schedules.endDate, INTERVAL 1 DAY)))
ELSE SELECT Schedules.endDate

你可以用括号写一个合适的IF

IF(TIME(Schedules.startDate)>TIME(Schedules.endDate),
   DATE(DATE_ADD(Schedules.endDate, INTERVAL 1 DAY)),
   Schedules.endDate)

或者你可以写一个CASE

CASE WHEN TIME(Schedules.startDate)>TIME(Schedules.endDate)
     THEN DATE(DATE_ADD(Schedules.endDate, INTERVAL 1 DAY))
     ELSE Schedules.endDate
END

在任何一种情况下,省略所有这些额外的SELECT关键字,因为你没有在那里执行子查询,只是评估表达式。