2012-03-01 55 views
0

有時我用這個sql查詢從我的帖子表中刪除重複的帖子。 但它需要很長時間才能完成,讓我的域名無法訪問像5分鐘。 看起來這是一個沉重的SQL服務器,這是一種使它更輕,更快的方法嗎?如何讓這個沉重的SQL查詢更輕?

DELETE FROM hotaru_posts WHERE post_id NOT IN (SELECT a.post_id FROM (SELECT post_title, post_id FROM hotaru_posts GROUP BY post_title) a) 

的最佳和最快的查詢,這是

delete from hotaru_posts where post_id in (
    select post_id from (
    select post_id from hotaru_posts a group by post_title having count(post_title) > 1 
) b 
) 

這個查詢只花了0.0603秒。而fisrt查詢花了超過5分鐘。 (笑)

+0

目前的工作?它不應該:你正在'GROUP BY post_title'中選擇一個非聚合的'post_id',這是不正確的。 – dasblinkenlight 2012-03-01 20:51:47

+0

@dasblinkenlight:是的,但是,IIRC,MySQL會在這種情況下從組中選擇一個未定值。 – 2012-03-01 20:53:10

+0

@SergioTulentsev換句話說,這個聲明刪除隨機重複:) – dasblinkenlight 2012-03-01 20:57:59

回答

0

的最佳和最快的查詢,這是

delete from hotaru_posts where post_id in (
    select post_id from (
    select post_id from hotaru_posts a group by post_title having count(post_title) > 1 
) b 
) 

這個查詢只花了0.0603秒。而fisrt查詢花了超過5分鐘。 (笑)

1

這項工作?

DELETE FROM hotaru_posts 
WHERE post_id IN (
    SELECT post_id 
    FROM (
     SELECT MAX(post_id) 
     FROM hotaru_posts a 
     GROUP BY post_title 
     HAVING COUNT(post_title) > 1 
    ) b 
) 
+0

會這樣工作嗎?你告訴我,我不敢測試它,因爲這是我的生活網站。 – 2012-03-01 21:09:06

+1

@LucasMatos:複製並測試。沒有你的數據的副本是一件好事。 – 2012-03-01 21:10:09

+0

'CREATE TABLE testTable AS SELECT * FROM hotaru_posts' - 將複製您的表並將其命名爲'testTable'嘗試在該表上運行此查詢。 – Travesty3 2012-03-01 21:11:40