在笔记6中使用说过比from中使用select有一种更加简单的方法view。
use sql_invoicing;
create view sales_by_clients as
select
c.client_id,
c.name,
SUM(invoice_total) as total_sales
from clients c
join invoices i using (client_id)
group by client_id,name
可以看到在左边显示的表中有sales_by_clients,可以像正常的表对齐进行操作。
注意:view不存储数据,数据存储在自己本身的库中
重新创建view的方法
在同时无以下语句的时候,VIEW是一个可更新VIEW
一般在对一个数据库无法直接操作或者权限受安全限制的时候,可以使用view来代替更新操作操作。会修改原先的table。
use sql_invoicing;
create or replace view invoices_with_balance as
select
invoice_id,number,client_id,invoice_total,payment_total,
invoice_total - payment_total as balance,
invoice_date,due_date,payment_date
from invoices
where (invoice_total - payment_total ) > 0
如上形成的view满足上面的四个条件,是个可以更新的表
//删除invoice_id 为1的行
DELETE from invoices_with_balance
where invoice_id = 1
//更新一组数据
update invoices_with_balance
set due_date = DATE_ADD(due_date,interval 2 DAY)
where invoice_id = 2
对于inert into操作,view必须有依赖表的所有column
对视图的操作,在update或者delete的时候,有些行将消失
update invoices_with_balance
//因为view在创建是需要满足where (invoice_total - payment_total ) > 0 ,此时已经不满足所以不见了
set payment_total = invoice_total
where invoice_id = 2
此时invoice_id = 2消失不显示,这不是我们想要的结果,为了保证能够正常显示,需要with option check
use sql_invoicing;
create or replace view invoices_with_balance as
select
invoice_id,number,client_id,invoice_total,payment_total,
invoice_total - payment_total as balance,
invoice_date,due_date,payment_date
from invoices
where (invoice_total - payment_total ) > 0
with option check