CREATEVIEW sales_by_client AS SELECT c.client_id, c.name, SUM(invoice_total) AS total_sales FROM clients c JOIN invoices i USING (client_id) GROUPBY client_id, name
可以在”Views”看到这个视图.可以像使用table一样用视图.
2 更改或删除视图
删除视图
1
DROPVIEW sales_by_client
更改视图
1 2 3 4 5 6 7 8 9 10
USE sql_invoicing;
CREATEORREPLACEVIEW sales_by_client AS-- create or replace SELECT c.client_id, c.name, SUM(invoice_total) AS total_sales FROM clients c JOIN invoices i USING (client_id) GROUPBY client_id, name
3 可更新视图
如果视图中没有:
DISTINCT Aggregate Functions (MIN, MAX, SUM) GROUP BY / HAVING UNION
就是可更新视图,就可以增删改:
比如:
1 2 3 4 5 6 7 8 9 10 11 12
CREATEORREPLACEVIEW invoices_with_balance AS SELECT invoice_id, number, client_id, invoice_total, payment_total, invoice_total - payment_total AS balance, due_date, payment_date FROM invoices WHERE (invoice_total - payment_total) > 0
invoices_with_balance 就是可更新视图,可以增删改:
1 2
DELETEFROM invoices_with_balance WHERE invoice_id = 1
1 2 3
UPDATE invoices_with_balance SET due_date = DATE_ADD(due_date, INTERVAL5DAY) WHERE invoice_id = 2
4 WITH OPTION CHECK 子句
上例中,进行如下更改:
1 2 3
UPDATE invoices_with_balance SET payment_total = invoice_total WHERE invoice_id = 2