Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Tạo View MySQL lấy giá trị theo điều kiện (WHERE)

Tạo view lọc dữ liệu theo điều kiện: dùng mệnh đề WHERE trong câu lệnh CREATE VIEW.

Cú pháp

Create View view_name AS Select_statements FROM table WHERE condition(s);

Ví dụ

Bảng Student_info:

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  |
+------+---------+------------+------------+
4 rows in set (0.08 sec)

Tạo view Info chỉ lấy môn Computers:

mysql> Create OR Replace VIEW Info AS Select Id, Name, Address, Subject from student_info WHERE Subject = 'Computers';
Query OK, 0 rows affected (0.46 sec)
mysql> Select * from info;
+------+-------+---------+-----------+
| Id   | Name  | Address | Subject   |
+------+-------+---------+-----------+
|  125 | Raman | Shimla  | Computers |
|  130 | Ram   | Jhansi  | Computers |
+------+-------+---------+-----------+
2 rows in set (0.00 sec)