การจัดการข้อมูลซ้ำ

การปรับปรุงประสิทธิภาพคิวรีใน SQL Server

Dean Smith

Founder, Atamai Analytics

คิวรีที่คืนค่าข้อมูลซ้ำ

SELECT PlayerName,
       Team
FROM PlayerStats; 
PlayerName Team
... ...
Emmanuel Mudiay DEN
Emmanuel Mudiay NYK
Enes Kanter NYK
Eric Bledsoe PHO
Eric Bledsoe MIL
... ...
การปรับปรุงประสิทธิภาพคิวรีใน SQL Server

ลบข้อมูลซ้ำด้วย DISTINCT()

SELECT DISTINCT(PlayerName)
FROM PlayerStats;
PlayerName
...
Emmanuel Mudiay
Enes Kanter
Eric Bledsoe
Eric Gordon
Eric Moreland
...
การปรับปรุงประสิทธิภาพคิวรีใน SQL Server

ใช้ GROUP BY แทน DISTINCT()

SELECT DISTINCT(PlayerName)
FROM PlayerStats;
SELECT PlayerName
FROM PlayerStats 
GROUP BY PlayerName;
การปรับปรุงประสิทธิภาพคิวรีใน SQL Server

ใช้ GROUP BY แทน DISTINCT()

SELECT DISTINCT(PlayerName)
FROM PlayerStats;
SELECT PlayerName
FROM PlayerStats 
GROUP BY PlayerName;
SELECT PlayerName,
    COUNT(Team) AS TeamsPlayedFor
FROM PlayerStats 
GROUP BY PlayerName;
PlayerName TeamsPlayedFor
... ...
Emmanuel Mudiay 2
Enes Kanter 1
Eric Bledsoe 2
Eric Gordon 1
Eric Moreland 1
... ...
การปรับปรุงประสิทธิภาพคิวรีใน SQL Server

มีวิธีอื่นอีกไหม?

SELECT PlayerName
FROM Players;
PlayerName
...
Emmanuel Mudiay
Enes Kanter
Eric Bledsoe
Eric Gordon
Eric Moreland
...
การปรับปรุงประสิทธิภาพคิวรีใน SQL Server

ตาราง Fruits

Fruits1

FruitName FruitType
Grapefruit Citrus
Orange Citrus
Peach Stone
Strawberry Berry

Fruits2

FruitName FruitType
Marionberry Berry
Orange Citrus
Plum Stone
Strawberry Berry
การปรับปรุงประสิทธิภาพคิวรีใน SQL Server

ผลไม้ที่ซ้ำกัน

 

 

 

  • Orange และ Strawberry ซ้ำกัน

Fruits1 ต่อท้าย Fruits2

FruitName FruitType
... ...
Orange Citrus
Orange Citrus
Plum Stone
Strawberry Berry
Strawberry Berry
การปรับปรุงประสิทธิภาพคิวรีใน SQL Server

ลบข้อมูลซ้ำด้วย UNION

SELECT FruitName, FruitType
FROM Fruits1

UNION

SELECT FruitName, FruitType
FROM Fruits2
FruitName FruitType
Grapefruit Citrus
Orange Citrus
Peach Stone
Strawberry Berry
Marionberry Berry
Plum Stone
การปรับปรุงประสิทธิภาพคิวรีใน SQL Server

แล้ว UNION ALL ล่ะ?

 

  • UNION ALL
    • ต่อแถวจากตารางตั้งแต่หนึ่งตารางขึ้นไป และ ไม่ ลบแถวที่ซ้ำกัน

 

  • UNION
    • ต่อแถวจากตารางตั้งแต่หนึ่งตารางขึ้นไป และลบแถวที่ซ้ำกันออก
การปรับปรุงประสิทธิภาพคิวรีใน SQL Server

DISTINCT() และ UNION

  • ใช้ด้วยความระมัดระวัง
  • อาจใช้กลไกเรียงลำดับภายในเพื่อตรวจสอบข้อมูลซ้ำ
  • อาจทำให้คิวรีใช้เวลานานขึ้น
การปรับปรุงประสิทธิภาพคิวรีใน SQL Server

การใช้ DISTINCT()

ก่อนใช้ DISTINCT() ควรถามตัวเองว่า:

  • มีวิธีอื่นที่ใช้แทนได้ไหม?
    • เช่น ใช้ตารางที่มี unique key แทน
  • คิวรีนี้ใช้ฟังก์ชัน aggregate หรือไม่?
    • ถ้าใช่ ให้จัดกลุ่มด้วย GROUP BY
การปรับปรุงประสิทธิภาพคิวรีใน SQL Server

การใช้ UNION

ก่อนใช้ UNION ควรถามตัวเองว่า:

  • ยอมรับแถวที่ซ้ำกันได้ไหม?
  • การต่อคิวรีจะสร้างแถวซ้ำหรือไม่?
  • หากยอมรับแถวซ้ำได้ หรือไม่มีแถวซ้ำเกิดขึ้น ให้พิจารณาใช้ UNION ALL
การปรับปรุงประสิทธิภาพคิวรีใน SQL Server

มาฝึกกันเถอะ!

การปรับปรุงประสิทธิภาพคิวรีใน SQL Server

Preparing Video For Download...