gpt4 book ai didi

mysql - 我无法从具有外部连接的 View 进行更新

转载 作者:行者123 更新时间:2023-11-30 21:48:27 26 4
gpt4 key购买 nike

我正在使用 MySQL 学习 SQL,当我尝试从具有外部连接的 View 更新时遇到问题

这是一个例子:

DROP TABLE IF EXISTS t1;
CREATE TABLE IF NOT EXISTS t1 (
id tinyint(3) UNSIGNED NOT NULL AUTO_INCREMENT,
t2_id tinyint(3) UNSIGNED DEFAULT NULL,
col3 varchar(255) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO t1 (id, t2_id, col3) VALUES
(1, 1, 'a'),
(2, 1, 'b'),
(3, 2, '3'),
(4, 2, '7'),
(5, NULL, '!');

DROP TABLE IF EXISTS t2;
CREATE TABLE IF NOT EXISTS t2 (
id tinyint(3) UNSIGNED NOT NULL AUTO_INCREMENT,
col2 varchar(255) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO t2 (id, col2) VALUES
(1, 'Character'),
(2, 'Number');

CREATE OR REPLACE
VIEW v_t1_details
AS SELECT t1.id, t2.col2, t1.col3
FROM t1
LEFT JOIN t2 ON t1.t2_id = t2.id;

我在 MySQL 5.7(5.7.14 和 5.7.19,在两个版本之间完全卸载并重新安装),这是我使用此查询时发生的情况:

UPDATE v_t1_details SET col3 = 'c' WHERE id = 2;

#1288 - The target table v_t1_details of the UPDATE is not updatable

我知道无法将外部连接与插入请求一起使用,但我在我的类(class)或更新的 MySQL 文档中没有看到类似的东西,所以我想知道为什么它不起作用。

感谢您的宝贵时间。

最佳答案

你不能更新 SQL VIEW - 一般而言

https://en.wikipedia.org/wiki/View_(SQL)

In a database, a view is the result set of a stored query on the data, which the database users can query just as they would in a persistent database collection object. This pre-established query command is kept in the database dictionary. Unlike ordinary base tables in a relational database, a view does not form part of the physical schema: as a result set, it is a virtual table computed or collated dynamically from data in the database when access to that view is requested.

https://www.codeproject.com/Tips/639239/Creating-and-Usage-of-View-in-SQL

A view is virtual, the data from a view is not stored physically. It is a set of queries that, when applied to one or more tables, is stored in the database as an object. A view encapsulates the name of the table. A virtual table contains column and data from multiple tables.

但多亏了@Thibaut,事实上你可以在有一定限制的情况下使用 mySQL

https://dev.mysql.com/doc/refman/5.7/en/view-updatability.html

With respect to insertability (being updatable with INSERT statements), an updatable view is insertable if it also satisfies these additional requirements for the view columns:

There must be no duplicate view column names.

The view must contain all columns in the base table that do not have a default value.

The view columns must be simple column references. They must not be expressions, such as these:

关于mysql - 我无法从具有外部连接的 View 进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48391240/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com