Làm việc với truy vấn MySQL WHERE..OR nhiều điều kiện OR. Có phương án thay thế?
Có, phương án thay thế cho MySQL "WHERE..OR" là sử dụng REGEXP.
Hãy tạo một bảng trước:
mysql> create table DemoTable684(EmployeeInformation text); Query OK, 0 rows affected (0.68 sec)
Chèn một số bản ghi vào bảng bằng lệnh insert:
mysql> insert into DemoTable684 values('John 21 Google');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable684 values('Carol 23 Amazon');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable684 values('Carol 26 Flipkart');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable684 values('David 29 Microsoft');
Query OK, 1 row affected (0.18 sec)
Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select:
mysql> select * from DemoTable684;
Điều này sẽ tạo ra đầu ra sau:
+---------------------+ | EmployeeInformation | +---------------------+ | John 21 Google | | Carol 23 Amazon | | Carol 26 Flipkart | | David 29 Microsoft | +---------------------+ 4 rows in set (0.00 sec)
Truy vấn sau triển khai MySQL where...OR sử dụng REGEXP:
mysql> select * from DemoTable684 where EmployeeInformation REGEXP '(David|29|Microsoft)';
Điều này sẽ tạo ra đầu ra sau:
+---------------------+ | EmployeeInformation | +---------------------+ | David 29 Microsoft | +---------------------+ 1 row in set (0.00 sec)
Giải thích: REGEXP '(David|29|Microsoft)' khớp nếu chuỗi chứa bất kỳ mẫu nào trong ngoặc (OR logic). Hiệu quả hơn nhiều so với nhiều OR LIKE khi có nhiều điều kiện.