视图是从数据库中的一个或多个表中导出来的虚拟表,起作用是方便用户对数据的操作。
视图是存储在数据库汇总的查询的sql语句
1,创建视图
- mysql> create view
- -> user_view(username,password)
- -> as select username,password from user
- -> ;
- Query OK, 0 rows affected (0.09 sec)
2,修改视图
- mysql> create or replace view user_view(username) as select username from user;
- Query OK, 0 rows affected (0.19 sec)
- mysql> desc user_view;
- +----------+-------------+------+-----+---------+-------+
- | Field | Type | Null | Key | Default | Extra |
- +----------+-------------+------+-----+---------+-------+
- | username | varchar(50) | NO | | NULL | |
- +----------+-------------+------+-----+---------+-------+
- 1 row in set (0.05 sec)
3,操作视图的时候,就是在操作一个表格,可以把视图当做表处理
- mysql> insert into user_view values('1','1');
- Query OK, 1 row affected (0.06 sec)
- mysql> select * from user_view;
- +----------+----------+
- | username | password |
- +----------+----------+
- | kenan | kenan |
- | kenan | lele |
- | lele | lele |
- | 1 | 1 |
- +----------+----------+
- 4 rows in set (0.00 sec)
- mysql> select * from user;
- +----+----------+----------+---------------------+
- | id | username | password | createtime |
- +----+----------+----------+---------------------+
- | 1 | kenan | kenan | 2012-10-31 15:32:26 |
- | 3 | kenan | lele | 2012-10-31 15:32:26 |
- | 4 | lele | lele | NULL |
- | 5 | 1 | 1 | NULL |
- +----+----------+----------+---------------------+
- 4 rows in set (0.00 sec)
4,删除视图
- mysql> drop view if exists user_view;
- Query OK, 0 rows affected (0.00 sec)
- mysql> desc user_view;
- ERROR 1146 (42S02): Table 'test.user_view' doesn't exist