1. 程式人生 > >Leetcode之資料庫刷題(一)

Leetcode之資料庫刷題(一)

1:刪除重複的郵箱

DELETE FROM Person WHERE Id NOT IN (SELECT Id FROM (SELECT 
MIN(Id) Id FROM Person GROUP BY Email) p);

DELETE p2 FROM Person p1 JOIN Person p2 
ON p2.Email = p1.Email WHERE p2.Id > p1.Id;

DELETE p2 FROM Person p1, Person p2 WHERE p1.Email = p2.Email 
AND p2.Id > p1.Id;
select
w1.Id from Weather w1,Weather w2 where w2.Date=date_sub(w1.Date,interval 1 day) and w2.Temperature<w1.Temperature

重點:
mysql 獲取日期前一天 後一天
date_sub(curdate(),interval 1 day) 表示 2016-07-31
date_sub(curdate(),interval -1 day) 2016-08-02

解法1:

SELECT w1.Id FROM Weather w1, Weather w2 
WHERE w1.Temperature > w2.Temperature
 AND
DATEDIFF(w1.Date, w2.Date) = 1;

下面這種解法我們使用了MySQL的TO_DAYS函式,用來將日期換算成天數,其餘跟上面相同。

解法二:

SELECT w1.Id FROM Weather w1, Weather w2
WHERE w1.Temperature > w2.Temperature 
AND TO_DAYS(w1.Date) = TO_DAYS(w2.Date) + 1;