Re: [SQL ] 大量刪除資料的問題

看板Database作者 (X票已賣出 別騷擾我啦= =)時間16年前 (2009/06/09 03:34), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/5 (看更多)
java的作法(寫個大概) Connection con1 = DriverManager.getConnection(uri,name,password); Connection con2 = DriverManager.getConnection(uri,name,password); con2.setAutoCommit(false); Statement stmt = con1.createStatement(); Statement stmt2 = con2.createStatement(); ResultSet result = stmt.executeQuery("撈出你要刪除的SQL"); while(result.next(){ stmt2.executeUpdate("預刪除的SQL"); } con2.commit(); result.close(); con1.close(); con2.close(); ※ 引述《bobju (寶貝豬)》之銘言: : //1 先檢查url_id有沒有設索引? 有設沒設差很多. : 設好索引後.. : //2 先把筆數超過N筆的url找出來: : $link=資料庫連線(); : $sql=" : select url_id,count(*) as count : from url_detail_history : group by url_id : having count(*)>1500"; : $rs=mysql_query($sql,$link); : //3 承2, 用php撈出每一組 url_id,count 再代入另一組sql語法: : while($r=mysql_fetch_assoc($rs)){ : //以下這種 delete from ... limit 的用法, 我似乎沒用過. 但看mysql : //官網有這種寫法: http://dev.mysql.com/doc/refman/5.0/en/delete.html : //所以應該可以才是. : sprintf(" : delete : from url_detail_history : where url_id=%d : order by id asc : limit %d", : $r['url_id'] : $r['count']-1500 : ); : mysql_query($sql,$link); : } // end while : 沒測試過, 也沒資料可測試. 所以不保證能run, 僅供參考. : 若有意願採用風險請自負. ^^! : ※ 引述《roga (凝視)》之銘言: : : 環境介紹:使用 DB 是 MySQL : : 資料表結構: : : url_detail_history 資料表 : : +--------------+---------------------+------+ : : | Field | Type | Null | : : +--------------+---------------------+------+ : : | id | bigint(11) unsigned | NO | -> 有 Auto_increment : : | url_id | int(11) | NO | : : | visitor_ip | varchar(15) | NO | : : | visitor_fqdn | varchar(100) | NO | : : | visitor_time | timestamp | NO | -> CURRENT_TIMESTAMP : : +--------------+---------------------+------+ : : 現在裡面有許多筆資料, : : SELECT COUNT(id), url_id from url_detail_history GROUP BY url_id : : 這句語法可以得知每個 url_id 有幾筆資料。 : : 因為前幾天程式上的疏忽,小弟寫錯了一些地方, : : 以至於資料表非常龐大,我想請問板上前輩們, : : 有沒有辦法直接用 SQL 語法執行,每個 url_id 只要總數 : : 超過 N 筆資料就刪除到只剩下 N 筆為止, : : 當然, id 越大代表資料越新,必須能從小的 id 開始刪起。 : : 我有寫一段程式來跑但是效能不彰, : : loading 飆到 100 多,拉牛上樹慘不忍睹.. : : foreach( $url_id ) { : : do { : : $ID = SELECT min(id) FROM table WHERE url_id = $url_id : : $COUNT = (再從資料表算 url_id 有幾筆) : : DELETE FROM table where id = $ID : : } while( $COUNT < 1501) : : } : : 這樣作法效能很差,不想這麼暴力解這個問題, : : 想請教前輩不知道有沒有比較好的辦法...謝謝 -- ╱ ◤◥╲ ╱╱◤◥你 我◤顏 ◥ △_▂△ ___ │/◤叔 敢 就 — — - - ╱ ╲ ⊙ ⊙ 動 幹 ◣_○_◢ \\\\ \│﹣ ﹣│ ◣_皿_◢ 我 你 ◥◣◥∞)///◤◢◤ 的 的 ╲┴ /─ 馬 狗 mroscarψ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 219.86.130.111
文章代碼(AID): #1ABMVGuQ (Database)
文章代碼(AID): #1ABMVGuQ (Database)