






















下面讲 SQL 视图的创建、修改和可更新视图的用法,跟着注释一步步来。
学习内容
示例代码与讲解
1. 创建视图
SELECT
client_id,
name,
SUM(invoice_total) AS total_sales
FROM clients c
JOIN invoices USING (client_id)
GROUP BY client_id, name;
CREATE VIEW sales_by_client AS
SELECT
client_id,
name,
SUM(invoice_total) AS total_sales
FROM clients c
JOIN invoices USING (client_id)
GROUP BY client_id, name;
SELECT *
FROM sales_by_client
ORDER BY total_sales DESC;
SELECT *
FROM sales_by_client
JOIN clients USING (client_id);
2. 修改视图
DROP VIEW sales_by_client;
CREATE OR REPLACE VIEW client_balance AS
SELECT
client_id,
name,
SUM(invoice_total - payment_total) AS Balance
FROM clients
JOIN invoices USING (client_id)
GROUP BY client_id, name;
3. 可更新视图
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;
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;
4. WITH CHECK OPTION
UPDATE invoices_with_balance
SET invoice_total = payment_total
WHERE invoice_id = 2;
CREATE OR REPLACE VIEW invoices_with_balance1 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 CHECK OPTION;
UPDATE invoices_with_balance1
SET invoice_total = payment_total
WHERE invoice_id = 3;
作业
1. 创建视图
CREATE VIEW client_balance AS
SELECT
client_id,
name,
SUM(invoice_total - payment_total) AS Balance
FROM clients
JOIN invoices USING (client_id)
GROUP BY client_id, name;
总结
讲了怎么创建视图、改视图,还弄了可更新视图,带上 WITH CHECK OPTION 防跑偏。用的 sql_invoicing 数据库。接下来看存储过程和触发器。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。