Home > Database > Mysql Tutorial > body text

How to create a MySQL view that gets values ​​from a table based on certain conditions?

PHPz
Release: 2023-09-07 23:17:02
forward
1324 people have browsed it

如何创建一个 MySQL 视图,根据某些条件从表中获取值?

If we want to create a view that gets values ​​from a table based on some specific conditions, then we must use the WHERE clause while creating the view. The value depending on the WHERE clause will be stored in the view. The syntax for creating a MySQL view using the WHERE clause is as follows -

Syntax

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

Example

To illustrate the above concept, we use the following data from the table "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)
Copy after login

Now, with the help of the following query, we will create the view name "Info" with the condition of storing rows with only Computer as subject. So, we need to use WHERE clause while creating the view as shown below -

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)
Copy after login

The above is the detailed content of How to create a MySQL view that gets values ​​from a table based on certain conditions?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template