Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

MySQL: ค้นหาข้อมูลสลับกัน (Alternative Records) ด้วย OR

การใช้ OR เพื่อเลือกแถวสลับกัน

หากต้องการเลือกแถวที่ ID เป็นค่าคู่ หรือค่าเฉพาะบางค่า ใช้เงื่อนไข OR รวมหลายเงื่อนไข

ตัวอย่าง: เลือก ID 2, 4, 6 (แถวคู่)

mysql> create table DemoTable772 (
    Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    Name varchar(100),
    Age int );
Query OK, 0 rows affected (0.76 sec)
mysql> insert into DemoTable772(Name,Age) values('Chris',21);
mysql> insert into DemoTable772(Name,Age) values('Robert',26);
mysql> insert into DemoTable772(Name,Age) values('Mike',27);
mysql> insert into DemoTable772(Name,Age) values('Sam',24);
mysql> insert into DemoTable772(Name,Age) values('Carol',28);
mysql> insert into DemoTable772(Name,Age) values('David',25);

คำสั่ง SELECT ด้วย OR

mysql> select * from DemoTable772 where Id=2 OR Id=4 OR Id=6;

ผลลัพธ์:

+----+--------+------+
| Id | Name   | Age  |
+----+--------+------+
| 2  | Robert | 26   |
| 4  | Sam    | 24   |
| 6  | David  | 25   |
+----+--------+------+

วิธีที่ดีกว่า: ใช้ IN

mysql> select * from DemoTable772 where Id IN (2,4,6);

ให้ผลลัพธ์เหมือนกัน แต่เขียนสั้นกว่า อ่านง่ายกว่า และประสิทธิภาพดีกว่า

การเลือกแถวสลับกันแบบ Dynamic (เลขคู่/เลขคี่)

-- เลือก ID คู่
select * from DemoTable772 where Id % 2 = 0;

-- เลือก ID คี่
select * from DemoTable772 where Id % 2 = 1;

สรุป

  • ใช้ OR สำหรับเงื่อนไขน้อยและเฉพาะเจาะจง
  • ใช้ IN (...) สำหรับรายการค่ามากกว่า 2-3 ค่า
  • ใช้ Modulo (%) สำหรับรูปแบบสลับกันแบบมีกฎคงที่