标签:mysql
数据准备
创建数据库、导入数据
[root@localhost ~]# mysql -uroot -p -e"create database viewdb;"
Enter password:
[root@localhost ~]# mysql -uroot -p viewdb< viewdb.sql
Enter password:
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| db2 |
| liujing |
| mysql |
| performance_schema |
| sys |
| viewdb |
| worlddb |
| xiaowei |
+--------------------+
9 rows in set (0.13 sec)
mysql> show tables;
+------------------+
| Tables_in_viewdb |
+------------------+
| user |
| userinfo |
+------------------+
2 rows in set (0.00 sec)
视图概述
视图是一个虚拟表,是从数据库中一个或多个表中导出来的表。视图还可以从已经存在的视图的基础上定义。
视图的作用
1、简化工作
2、提高安全性
3、逻辑独立
创建视图的语法
CREATE [OR REPLACE] [ALGORITHM] ={undefined|MERGE|TEMPTABLE}]
VIEW view_name [(column_list)]
AS SELECT_statement
[WITH[CASCADED|LOCAL] CHECK OPTION]
ALGORITHM用于设定视图的算法
CASCADED|LOCAL为限定条件。
CASCADED:默认值,更新时必须满足所有相关视图和表的条件。
LOCAL:更新时仅满足该视图本身定义的条件即可。
创建单表视图
mysql> create view view_user as selectname,age from user;
Query OK, 0 rows affected (0.01 sec)
查看
mysql> select name,age from user;
+---------+------+
| name | age |
+---------+------+
| TubeLiu | 10 |
| Kevin | 20 |
| Mark | 30 |
| July | 40 |
+---------+------+
4 rows in set (0.00 sec)
mysql> select * from view_user;
+---------+------+
| name | age |
+---------+------+
| TubeLiu | 10 |
| Kevin | 20 |
| Mark | 30 |
| July | 40 |
+---------+------+
4 rows in set (0.00 sec)
更新了视图中的数据
mysql> update view_user set age = 20where name=‘Tubeliu‘;
Query OK, 1 row affected (0.10 sec)
Rows matched: 1 Changed: 1 Warnings: 0
查看
mysql> select * from view_user;
+---------+------+
| name | age |
+---------+------+
| TubeLiu | 20 |
| Kevin | 20 |
| Mark | 30 |
| July | 40 |
+---------+------+
4 rows in set (0.00 sec)
mysql> select name,age from user;
+---------+------+
| name | age |
+---------+------+
| TubeLiu | 20 |
| Kevin | 20 |
| Mark | 30 |
| July | 40 |
+---------+------+
4 rows in set (0.00 sec)
对视图的操作也会影响真实表中的内容。
创建多表视图
mysql> create viewview_userinfo(name1,phone1) as select user.name,userinfo.phone fromuser,userinfo where id=fid;
Query OK, 0 rows affected (0.00 sec)
查看
mysql> select * from view_userinfo;
+---------+--------+
| name1 | phone1 |
+---------+--------+
| TubeLiu | 12345 |
| Kevin | 54321 |
| Mark | 32145 |
| July | 34521 |
+---------+--------+
4 rows in set (0.00 sec)
mysql> select user.name,userinfo.phonefrom user,userinfo where id=fid;
+---------+-------+
| name | phone |
+---------+-------+
| TubeLiu | 12345 |
| Kevin | 54321 |
| Mark | 32145 |
| July | 34521 |
+---------+-------+
4 rows in set (0.00 sec)
本文出自 “阳光的蜗牛” 博客,谢绝转载!
标签:mysql
原文地址:http://sunshinesnail.blog.51cto.com/1179761/1736791