网站建设 全网营销,沧州seo包年优化软件排名,常用的网站开发技术有哪几种,许昌网站推广公司1. 创建视图
因为越来越多的表连接子查询会十分复杂#xff0c;所以可以将这些查询or子查询存在视图里#xff0c;下一次还可以继续使用这些视图#xff0c;而不需要再写一次查询。 如#xff0c;在数据库【sql_invoicing】中写一段查询#xff0c;得到每位客户的…1. 创建视图
因为越来越多的表连接子查询会十分复杂所以可以将这些查询or子查询存在视图里下一次还可以继续使用这些视图而不需要再写一次查询。 如在数据库【sql_invoicing】中写一段查询得到每位客户的总销售额:
use sql_invoicing;select c.client_id,c.name,sum(invoice_total)as total_salesfrom clients cjoin invoices i using (client_id)
group by client_id, name
order by client_id 这样的查询十分频繁所以可以直接保存为视图在其他地方进行使用。
创建视图
use sql_invoicing;-- 创建视图
create view sales_by_client as
select c.client_id,c.name,sum(invoice_total)as total_salesfrom clients cjoin invoices i using (client_id)
group by client_id, name
order by client_id views中将会显示我们创建的视图 我们可以将视图视为一个表去进行操作比如对总的销售进行倒序排序
select *
from sales_by_client
order by client_id desc; 注意⚠️视图中不存储数据数据只储存于表中 【练习】创建一个视图显示每一个顾客的结余命名为“clients_balance”视图中包含client_id、name、balance
create view clients_balance as
select c.client_id,c.name,sum(invoice_total - payment_total) as balancefrom clients cjoin invoices i using (client_id)
group by client_id, name
order by client_id; 2. 更改或删除视图
方法一删除视图重新创建
drop view sales_by_client
方法二使用REPLACE关键字推荐
create or replace view sales_by_client as
select c.client_id,c.name,sum(invoice_total)as total_salesfrom clients cjoin invoices i using (client_id)
group by client_id, name
order by client_id; 为了防止视图丢掉一般情况下创建一个views的文件夹将创建视图的源代码进行存储团队或者按如下图所示的小按钮视图会以编辑模式打开 3. 可更新视图 可更新视图不包含以下语句可以在视图中更新数据 distinctaggregate functionsminmaxsumgroup by、havingunion 可更新视图可以使用于insert、update、delete语句中 创建一个有结余的视图其中结余支票总计-支付总计
use sql_invoicing;create or replace view invoices_with_balace 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 -- 无法使用balanace系统会告诉你没有这个列 这是一个可更细视图所以可以进行修改:
delete from invoices_with_balace
where invoice_id 1
4. WITH OPTION CHECK字句 修改上个视图中的2号将他的payment_total改成invoice_total update invoices_with_balace
set payment_total invoice_total
where invoice_id 2; 可以看到2消失了因为2计算出来的invoice_total-payment_total0不在视图范围内因此不会显示出来。 如果不想update或delete语句将行从视图中删除可以在视图代码中进行以下操作
use sql_invoicing;create or replace view invoices_with_balace 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 -- 无法使用balanace系统会告诉你没有这个列
with check option 在执行后可以发现报错也就是说如果在修改某一行时其结果可能会导致该行从视图里被删除就会有报错 5. 视图的其他优点 除了上述视图可以简化查询第二个优点就是可以减小数据库设计改动的影响。比如有一些操作需要修改列的信息但是直接动基础表可能会影响后续操作此时只需要修改视图代码。 第三个优点是可以使用视图限制基础表访问。比如在视图中可能会使用where字句筛选信息或者从基础表汇总删除一些列如果删除表中的一些列用户就只能通过视图来更新数据对于一个基础表有很多用户来访问时可以保证基础表的安全。