修改视图是指修改数据库中存在的视图,当基本表的某些字段发生变化时,可以通过修改视图来保持与基本表的一致性。
1. 用 CREATE OR REPLACE VIEW 语句修改视图
语法格式如下:
CREATE [OR REPLACE ] [ALGORITHM={ UNDEFINED | MERGE | TEMPTABLE }]
VIEW view_name [( column_list )]
AS SELECT_statement
[ WITH | [ CASCADED | LOCAL ] CHECK OPTION];
可以看到,修改视图的语句和创建视图的语句完全一样。当视图存在时,修改语句对视图进行修改;当视图不存在时,创建视图。【例】修改视图 view_t。
修改前:
- mysql> DESC view_t;
- +-----------------+------------+------+-----+---------+-------+
- | Field | Type | Null | Key | Default | Extra |
- +-----------------+------------+------+-----+---------+-------+
- | quantity | int(11) | YES | | NULL | |
- | price | int(11) | YES | | NULL | |
- | quantity *price | bigint(21) | YES | | NULL | |
- +-----------------+------------+------+-----+---------+-------+
修改语句:
- mysql> CREATE OR REPLACE VIEW view_t AS SELECT * FROM t;
- Query OK, 0 rows affected (0.07 sec)
修改后:
- mysql> DESC view_t;
- +----------+---------+------+-----+---------+-------+
- | Field | Type | Null | Key | Default | Extra |
- +----------+---------+------+-----+---------+-------+
- | quantity | int(11) | YES | | NULL | |
- | price | int(11) | YES | | NULL | |
- +----------+---------+------+-----+---------+-------+
2. 用 ALTER 语句修改视图
语法格式如下:
ALTER [ALGORITHM={ UNDEFINED | MERGE | TEMPTABLE }]
VIEW view_name [( column_list )]
AS SELECT_statement
[ WITH | [ CASCADED | LOCAL ] CHECK OPTION];
【例】用 ALTER 语句修改视图 view_t。
修改前:
- mysql> DESC view_t;
- +----------+---------+------+-----+---------+-------+
- | Field | Type | Null | Key | Default | Extra |
- +----------+---------+------+-----+---------+-------+
- | quantity | int(11) | YES | | NULL | |
- | price | int(11) | YES | | NULL | |
- +----------+---------+------+-----+---------+-------+
修改语句:
- mysql> ALTER VIEW view_t AS SELECT quantity FROM t;
- Query OK, 0 rows affected (0.04 sec)
修改后:
- mysql> DESC view_t;
- +----------+---------+------+-----+---------+-------+
- | Field | Type | Null | Key | Default | Extra |
- +----------+---------+------+-----+---------+-------+
- | quantity | int(11) | YES | | NULL | |
- +----------+---------+------+-----+---------+-------+
【注】参考于清华大学出版社《MySQL数据库应用案例课堂》2016年1月第1版