-2

我想在 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
)
4

2 回答 2

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
;
于 2013-01-23T08:25:07.060 回答
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关键字,因为您没有在那里执行子查询,只是评估表达式。

于 2013-01-23T08:03:51.097 回答