前幾天接到一個數(shù)據(jù)庫去重的需求果正,大概意思是這樣的:我們數(shù)據(jù)庫中有一個存儲用戶第三方信息的表檐春,因為之前程序漏洞導(dǎo)致記錄中一個用戶對應(yīng)了多個第三方信息。現(xiàn)在需要保證一個用戶ID只能有一條記錄硫戈,對于多條記錄的用戶ID保留最近綁定的記錄茶敏。
數(shù)據(jù)庫表結(jié)構(gòu)
user_thirdpart` (
USER_ID
int(11) NOT NULL COMMENT,
THIRD_MESSAGE
text CHARACTER,
GMT_CREATE
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)
解決方法
百度了各種方法之后還是后未能成功线梗,最終結(jié)合網(wǎng)上的方法解決椰于。具體sql如下
DELETE user_thirdpart
FROM user_thirdpart,
(
SELECT
user_id,
max(gmt_create) gmt_create
FROM
user_thirdpart
GROUP BY
user_id
HAVING
count(1) > 1
) temp
WHERE
user_thirdpart.user_id = temp.user_id
AND user_thirdpart.gmt_create < temp.gmt_create
sql解析:
- ( SELECT user_id, max(gmt_create) gmt_create FROM user_thirdpart GROUP BY user_id HAVING count(1) > 1) temp 從表中查詢出多次出現(xiàn)的user_id記錄,并返回創(chuàng)建時間最大的一條記錄作為臨時表 temp
- where user_thirdpart.user_id = temp.user_id AND user_thirdpart.gmt_create < temp.gmt_create關(guān)聯(lián)判斷重復(fù)條件的字段
- 刪除user_thirdpart中 where條件滿足的記錄