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

MySQL: ใช้ IN สำหรับ 2 คอลัมน์ (Row Constructor)

การใช้ IN กับ Tuple (Row Constructor)

MySQL รองรับการเปรียบเทียบหลายคอลัมน์พร้อมกันด้วย (col1, col2) IN ((val1, val2), (val3, val4), ...)

ตัวอย่าง

mysql> create table DemoTable810(First int, Second int);
Query OK, 0 rows affected (0.73 sec)
mysql> insert into DemoTable810 values(20,40);
mysql> insert into DemoTable810 values(70,90);
mysql> insert into DemoTable810 values(120,150);
mysql> insert into DemoTable810 values(78,128);

ค้นหาคู่ค่า (20,40) และ (120,150)

mysql> select * from DemoTable810 where (First,Second) IN ((120,150),(20,40));

ผลลัพธ์:

+-------+--------+
| First | Second |
+-------+--------+
| 20    | 40     |
| 120   | 150    |
+-------+--------+

การใช้งานอื่นๆ

-- ใน Subquery
SELECT * FROM orders 
WHERE (customer_id, order_date) IN (
    SELECT customer_id, MAX(order_date) FROM orders GROUP BY customer_id
);

-- กับ NOT IN
SELECT * FROM DemoTable810 WHERE (First,Second) NOT IN ((20,40),(70,90));

ข้อดี

  • อ่านง่ายกว่าเขียน AND/OR ซ้อนกัน
  • ประสิทธิภาพดี (Optimizer รองรับ)
  • เหมาะสำหรับ Composite Key หรือ Unique Constraint หลายคอลัมน์

สรุป

ใช้ (col1, col2) IN ((v1,v2), (v3,v4)) สำหรับจับคู่ค่าหลายคอลัมน์พร้อมกัน สะดวกและมีประสิทธิภาพ