mysql - 依赖于多个表的可更新 View

标签 mysql sql join view

我正在阅读 MySQL 中的可更新 View :

To be more specific, a view is not updatable if it contains any of the following: ....

Certain joins (see additional join discussion later in this section)

然后:

It is sometimes possible for a multiple-table view to be updatable, assuming that it can be processed with the MERGE algorithm. For this to work, the view must use an inner join (not an outer join or a UNION).

但是没有明确的例子,我没有成功更新我创建的涉及 NATURAL JOIN 的 View 。

依赖于可更新的多表 的 View 示例是什么?什么时候不呢?

最佳答案

示例表架构

CREATE TABLE customers(customer_id INT, `name` VARCHAR(32));
CREATE TABLE orders(order_id INT, customer_id INT, order_date DATE);

景色

CREATE VIEW vw_orders AS 
SELECT order_id, o.customer_id order_customer_id, c.customer_id, c.name customer_name, order_date
  FROM orders o INNER JOIN 
       customers c ON o.customer_id = c.customer_id;

然后你可以这样插入

INSERT INTO vw_orders (customer_id, customer_name) VALUES (1, 'Customer1');
INSERT INTO vw_orders (order_id, order_customer_id, order_date) VALUES (1, 1, CURDATE());

或更新

UPDATE vw_orders SET customer_name = 'Customer11' WHERE customer_id = 1;

注意:您无法使用一条语句在两个基础表中插入或更新值

这个声明

INSERT INTO vw_orders (customer_id, customer_name, order_id, order_customer_id, order_date) 
VALUES (2, 'Customer2', 2, 2, CURDATE());

将因错误而失败

Can not modify more than one base table through a join view 'vw_orders'

关于mysql - 依赖于多个表的可更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16012119/

相关文章:

mysql - 这是执行 MySQL 查询的最佳/有效方法

mysql - 计算具有 3 个列值相同 MySQL 的行的出现次数

PHP/MySQL - 编辑审批系统

mysql - 在 MySQL 结果旁边重复运行数字

sql - 在 SQL 或 MySQL 中,我们可以连接一个表和一个子查询结果吗?

mysql - 连接列上的 SQL 过滤器查询

mysql - MariaDB 显示警告而不是错误

mysql - MySQL 有没有办法让一个列只是对同一个表上另一列的引用?

php - 一个查询中两个表的 ORDER BY 结果

sql - MySQL 查询和文本搜索