MySQL刪除重複資料,只保留其中最大id的一條
阿新 • • 發佈:2018-11-04
今天同事寫了個刪除重複資料保留一條記錄的資料庫語句,問我錯在哪兒,正好給大家講講【注:以下語句只單對MYSQL資料庫】
語句 -- 問題:
delete from `show` where id not in ( select MAX(id) from `show` where led = 43 and location = "<===" and status = 1 ) and status = 1
SQL語句(查詢)-- 正確:
select id from `show` where id not in ( select * from ( select id from `show` group by led,location,status ) b ) and status = 1
SQL語句(刪除)-- 正確:
delete from `show` where id not in ( select * from ( select id from `show` group by led,location,status ) b ) and status = 1
有2個疑問點:
1、為什麼要套這樣一個select?因為 更新資料時使用了查詢,而查詢的資料又做更新的條件,mysql不支援這種方式
2、這句話中一定要取別名