SQL Command select ข้อมูลที่มี รหัสซ้ำกัน หรือ ID ซ้ำกัน
SQL Command วิธี select ข้อมูล แบบเอาแค่ ที่รหัสซ้ำกัน
หรือ จะกรองเอาแค่ ที่รหัสไม่ซ้ำกันก็ได้
ยกตัวอย่าง เรามี table ชือ my_table มี รหัสชื่อ f_id
ตัวอย่าง SQL Command ที่ใช้คือ
การใช้ group by + having + เทคนิคการ count
Select f_id,count(f_id) from my_table
group by f_id having count(f_id)>1
จากคำสั่งนี้เราจะได้ข้อมูลคือ f_id และก็ จำนวนที่มันซ้ำกันเช่น
1001 , 3
1002 ,10
1003 , 30
แล้วถ้าเราอยากได้ข้อมูลทั้งแถวต้องทำยังไง
เราไม่สามารถใส่ * หรือ ใส่ field เข้าไปมากกว่านี้ในคำสั่งที่มี group by เฉพาะ field นั้นๆ ได้
เทคนิคคือ การใช้ select ซ้อน select เช่น
ดึงข้อมูลทั้ง row ที่ รหัสซ้ำกัน
select * from my_table where f_id in (
Select f_id from my_table
group by f_id having count(f_id)>1)
ดึงข้อมูลทั้ง row ที่ รหัสไม่ซ้ำกัน
select * from my_table where f_id in (
Select f_id from my_table
group by f_id having count(f_id)=1)
หรือ
select * from my_table where f_id not in (
Select f_id from my_table
group by f_id having count(f_id)>1)
เอาจริงๆ มันก็สามารถใช้ได้กับทุก field ที่เราต้องการตรวจสอบแหละครับ