วิธีลบข้อมูลที่ซ้ำกันออกจากตารางสำหรับระบบฐานข้อมูล MySQL (How to delete duplicate records in a MySQL database)

คุณอาจจะเคยพบกับปัญหาที่ว่าข้อมูลในตารางนั้นมีข้อมูลซ้ำ ๆ วันนี้ผมก็พบเข้ากับตัวเอง ด้วยเหตุที่ว่าวันนี้เว็บของลูกค้าผมซึ่งสร้างด้วย Drupal ไม่สามารถเข้าไปดูในหน้าของ Organic Subgroup Module ได้เพราะว่าเกิด time out ทุกครั้งที่เข้าไปดูหน้านี้ ผมจึงคิดว่าปัญหาน่าจะอยู่จากระบบฐานข้อมูล ของ Organic Subgroup Module โดยข้อมูลของ Module นี้เก็บอยู่ในตารางเพียงตารางเดียวที่ชื่อว่า "og_ancestry" ซึ่งโครงสร้างข้อมูลในตารางนี้จะมีลักษณะเป็น Tree แน่นอนผมคิดว่าปัญหาน่าจะมาจากการที่มีการอ้างอิงของข้อมูล (reference) ที่ไม่ถูกต้องจนเกิดการอ้างอิงแบบวงวน (circular reference) ซึ่งทำให้ function ที่ query ข้อมูลในตารางนี้แบบ recursive นั้นทำงานไม่รู้จบ จึงเกิด time out ขึ้น ดังนั้นจึงลอง query ข้อมูลในตารางนี้ดู ผมก็พบว่าในตาราง "og_ancestry" นั้นมีข้อมูลซ้ำๆ กันเป็นจำนวนมาก เจองี้เข้าก็อึ้งสิครับ แล้วอย่างนี้ผมจะหาได้หรือเปล่าว่าข้อมูลอันไหนที่ทำให้เกิด loop? ดังนั้นผมจึงควรลบข้อมูลที่ซ้ำๆกันออกไปก่อนเพื่อให้ง่ายต่อการวิเศราะห์ข้อมูล แล้ววิธีการลบข้อมูลที่ซ้ำ ๆ กันล่ะจะทำได้อย่างไร?...

จริง ๆ ขั้นตอนมันก็ไม่มีอะไรซับซ้อนหรอกครับ แต่ผมเห็นว่ามีประโยชน์ดีก็อยากจะเผยแพร่ เรามาเริ่มกันเลยดีกว่า สมมติว่าตาราง "og_ancestry" มีโครงสร้างดังนี้

og_ancestry
Column Name Type
nid Integer
group_nid Integer
is_public Integer
  1. เราต้องสร้าง Temporary Table ที่ชื่อว่า "og_ancestry_temp" ซึ่งมีโครงสร้างเหมือนกับตางราง "og_ancestry" ด้วยคำสั่งต่อไปนี้:
    CREATE TEMPORARY TABLE
    og_ancestry_temp(nid INT, group_nid INT, is_public INT) TYPE=HEAP;
  2. จากนั้นเราก็นำเฉพาะค่าที่ไม่ซ้ำกันจากตาราง "og_ancestry" ไปใส่ในตาราง "og_ancestry_temp" ด้วยคำสั่งต่อไปนี้:
    INSERT INTO og_ancestry_temp(nid, group_nid, is_public)
    SELECT DISTINCT nid, group_nid, is_public FROM og_ancestry;
  3. ลบข้อมูลทั้งหมดในตาราง "og_ancestry" ด้วยคำสั่งต่อไปนี้:
    DELETE FROM og_ancestry;
  4. นำข้อมูลที่ไม่ซ้ำซึ่งเก็บอยู่ในตาราง "og_ancestry_temp" ใส่กลับคืนไปในตาราง "og_ancestry" ด้วยคำสั่งต่อไปนี้:
    INSERT INTO og_ancestry(nid, group_nid, is_public)
    SELECT DISTINCT nid, group_nid, is_public FROM og_ancestry_temp;
  5. ลบตาราง "og_ancestry_temp" ด้วยคำสั่งต่อไปนี้:
    DROP TABLE og_ancestry_temp;

เป็นอันเสร็จเรียบร้อย เพียงแค่นี้เราก็จะไม่มีข้อมูลที่ซ้ำกันอยู่ในตารางนี้แล้ว \@/

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd><img> <object> <embed> <param>
  • Lines and paragraphs break automatically.
  • Images can be added to this post.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.
ญาณรักข์ วรรณสาย