給定一個Weather
表,編寫一個SQL查詢來查找與以前(昨天的)日期相比溫度更高的全部日期的id。mysql
建立表和數據:sql
-- ---------------------------- -- Table structure for `weather` -- ---------------------------- DROP TABLE IF EXISTS `weather`; CREATE TABLE `weather` ( `Id` int(11) DEFAULT NULL, `RecordDate` date DEFAULT NULL, `Temperature` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of weather -- ---------------------------- INSERT INTO `weather` VALUES ('1','2015-01-01', '10'); INSERT INTO `weather` VALUES ('2','2015-01-02', '25'); INSERT INTO `weather` VALUES ('3','2015-01-03', '20'); INSERT INTO `weather` VALUES ('4','2015-01-04', '30');
解法:函數
1.思路簡單。表自鏈接,找出溫度比前一天高的行。spa
問題的關鍵是肯定日期的前一天。code
日期函數: DATEDIFF(date1,date2) ,返回date1與date2之間相差的天數。blog
SELECT W1.Id FROM weather AS W1 JOIN weather AS W2 ON (DATEDIFF(W1.RecordDate,W2.RecordDate) = 1 AND W1.Temperature > W2.Temperature)
2.一樣,函數: TIMESTAMPDIFF(unit,begin,end),返回begin與end之間相差多少個unit。unit爲DAY時,即爲相差「天」。get
SELECT W2.Id FROM weather AS W1 JOIN weather AS W2 ON (TIMESTAMPDIFF(DAY,W1.RecordDate,W2.RecordDate) = 1 AND W1.Temperature < W2.Temperature);
TO_DAYS函數,用來將日期換算整天數it
SELECT w1.Id FROM Weather w1, Weather w2 WHERE w1.Temperature > w2.Temperature AND TO_DAYS(w1.RecordDate)=TO_DAYS(w2.RecordDate) + 1;
使用Subdate函數,來實現日期減1class
SELECT w1.Id FROM Weather w1, Weather w2 WHERE w1.Temperature > w2.Temperature AND SUBDATE(w1.RecordDate, 1) = w2.RecordDate;