标签:sql查询 tables gen where test 理解 alter cat root
mysql视图是一个虚拟表,其内容由查询定义.
同真实的表一样,视图包含一系列带有名称的列和行数据
但是,视图并不在数据库中以存储的数据集形式存在
行和列数据来自,由定义视图的查询所引用的表,并且在引用视图时动态生成
mysql视图的作用类似于筛选,定义视图的筛选可以来自当前或其他数据库的一个或多个表,或者其他视图
通过视图进行查询没有任何限制,通过他们进行数据修改时的限制也很少
视图是存储在数据库中的sql查询语句
主要出于两种原因
语法
create view 视图名 as 查询语句
创建视图
mysql> create view u as
-> select user,host from mysql.user\G
Query OK, 0 rows affected (0.00 sec)
查看视图
mysql> select * from u\G
*************************** 1. row ***************************
user: mysql.session
host: localhost
*************************** 2. row ***************************
user: mysql.sys
host: localhost
*************************** 3. row ***************************
user: root
host: localhost
3 rows in set (0.00 sec)
准备数据
mysql> create database shop;
Query OK, 1 row affected (0.00 sec)
mysql> use shop;
mysql> create table product(
-> id int unsigned auto_increment primary key,
-> name varchar(60) not null,
-> price double not null
-> );
Query OK, 0 rows affected (0.01 sec)
mysql> insert into product(name,price) values
-> ('apple',10),
-> ('orange',5),
-> ('pear',9);
Query OK, 3 rows affected (0.01 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> create table purchase(
-> id int unsigned auto_increment primary key,
-> name varchar(60) not null,
-> quantity int not null default 0,
-> gen_time datetime not null
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> insert into purchase(name,quantity,gen_time)
-> values
-> ('apple',8,now()),
-> ('orange',5,now());
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
创建多表视图
mysql> create view purchase_detail as
-> select
-> a.name,a.price,
-> b.quantity,
-> a.price * b.quantity as total_value
-> from product a,purchase b
-> where a.name=b.name;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from purchase_detail\G
*************************** 1. row ***************************
name: apple
price: 10
quantity: 8
total_value: 80
*************************** 2. row ***************************
name: orange
price: 5
quantity: 5
total_value: 25
2 rows in set (0.00 sec)
查看视图名
mysql> show tables\G
*************************** 1. row ***************************
Tables_in_shop: product
*************************** 2. row ***************************
Tables_in_shop: purchase
*************************** 3. row ***************************
Tables_in_shop: purchase_detail
3 rows in set (0.00 sec)
查看某个数据库中所有视图详细信息
mysql> show table status from test\G
查看数据库test中视图名purchase_detail详细信息
mysql> show table status from shop like 'purchase_detail'\G
查看视图定义信息
mysql> show create view purchase_detail\G
查看视图结构
mysql> desc purchase_detail\G
方法一:删除后新创建
语法
drop view view_user;
方法二:alter修改视图
语法
alter view 视图名 as select语句;
标签:sql查询 tables gen where test 理解 alter cat root
原文地址:https://www.cnblogs.com/inmeditation/p/12236787.html