MySQL basis (4) | view

MySQL basis (4) | view


The basic syntax

1. Create

CREATE VIEW <视图名> AS <SELECT语句>

The syntax is described below.

  • <视图名>: Specifies the name of the view. The name must be unique in the database, not the same name as other tables or views.
  • <SELECT语句>: Specifies the SELECT statement to create a view that can be used to query multiple underlying table or source view.

The following restrictions exist for a given SELECT statement to create a view of:

  • CREATE VIEW addition to user permissions, also have associated permissions and other base view table involved in the operation.
  • SELECT statement can not refer to system or user variables .
  • SELECT statement can not contain a subquery in the FROM clause .
  • View definition can not refer to TEMPORARY tables (temporary tables) , you can not create a TEMPORARY view.

  • SELECT statement can not refer to prepared statement parameters .

  1. modify
ALTER VIEW <视图名> AS <SELECT语句>
  1. delete
DROP VIEW <视图名1> [ , <视图名2> …]

Example:

#创建数据表
create table mygoods(
  g_id int AUTO_INCREMENT primary key,
    g_name varchar(20),
    g_price double,
    g_count int
)engine=innodb default CHARSET=utf8;

create table myperson(
    p_id int AUTO_INCREMENT primary key,
    p_name varchar(20),
    g_id int,
    foreign key fk_pid(g_id)
    references mygoods(g_id)
);

#插入数据
insert into mygoods(g_name, g_price, g_count) select '梨', 2.2, 3;
insert into mygoods(g_name, g_price, g_count) select '苹果', 5.6, 2;
insert into myperson(p_name,g_id) select '小白',1;

#创建视图
CREATE VIEW v_mygoods
as select g_price, g_count, g_price * g_count as total from mygoods;
#查看视图
select * from v_mygoods;

create view v_myperson
as select a.p_name, b.g_price * b.g_count as tP from myperson a inner join mygoods b on a.g_id = b.g_id;

select * from v_myperson;

Guess you like

Origin www.cnblogs.com/iwsx/p/12348942.html