Toán tử LIKE trong MySQL được sử dụng để chọn dữ liệu dựa trên khớp mẫu (pattern matching). Tương tự, chúng ta có thể sử dụng toán tử LIKE với view để chọn dữ liệu cụ thể dựa trên khớp mẫu từ bảng cơ sở. Để hiểu khái niệm này, chúng ta sẽ sử dụng bảng cơ sở student_info với dữ liệu sau:
mysql> Select * from Student_info; +------+---------+------------+------------+ | id | Name | Address | Subject | +------+---------+------------+------------+ | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Chandigarh | Literature | | 125 | Raman | Shimla | Computers | | 130 | Ram | Jhansi | Computers | | 132 | Shyam | Chandigarh | Economics | | 133 | Mohan | Delhi | Computers | +------+---------+------------+------------+ 6 rows in set (0.00 sec)
Ví dụ
Truy vấn sau sẽ tạo một view tên Info để chọn các giá trị cụ thể dựa trên khớp mẫu bằng toán tử LIKE:
mysql> Create or Replace view Info AS SELECT * from student_info WHERE Name LIKE '%Ra%'; Query OK, 0 rows affected (0.11 sec) mysql> Select * from Info; +------+--------+------------+------------+ | id | Name | Address | Subject | +------+--------+------------+------------+ | 105 | Gaurav | Chandigarh | Literature | | 125 | Raman | Shimla | Computers | | 130 | Ram | Jhansi | Computers | +------+--------+------------+------------+ 3 rows in set (0.00 sec)
Chúng ta cũng có thể sử dụng NOT với toán tử LIKE như sau:
mysql> Create or Replace view Info AS SELECT * from student_info WHERE Name NOT LIKE '%Ra%'; Query OK, 0 rows affected (0.14 sec) mysql> Select * from info; +------+---------+------------+-----------+ | id | Name | Address | Subject | +------+---------+------------+-----------+ | 101 | YashPal | Amritsar | History | | 132 | Shyam | Chandigarh | Economics | | 133 | Mohan | Delhi | Computers | +------+---------+------------+-----------+ 3 rows in set (0.00 sec)