2013-01-23 129 views
-2

我想選擇日期時間日期,但如果的startDate的時間更多的則是結束日期的時間,然後添加一個一天結束日期的語句,這裏是我的代碼,但它不工作,感謝與MySQL的日期時間

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 
) 
+0

嘗試使用'CASE WHEN' –

回答

0

我爲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 
; 
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關鍵字,因爲你不在那裏執行子查詢,只是評估表達式。