是否可以自动更新视图列 (Mysql)?

Is it possible to update views columns automatically (Mysql)?

我有以下场景:

有一个数据库(主要)保存 'modules'、'menu' 等公共信息,每个项目都有一个数据库,其中每个 table 都有一个视图在主数据库中。例如:

主要

项目 1

创建的视图非常简单:

CREATE VIEW menu_view AS SELECT * FROM main.menu

现在,我必须为菜单创建一个 'order' 列,但视图列没有更新。

ALTER TABLE `menu` ADD `menu_order` INT NOT NULL AFTER `href`;

是否可以保持视图列更新,而不必每次我必须在主 table 中创建新列时手动执行?


OBS:有 10 多个项目...所以随着这个数字的增长,维护会变得更加困难

您正在使用 * 定义视图:

CREATE VIEW menu_view AS
    SELECT * FROM main.menu;

唉,* 是在 创建视图 时解释的,而不是在 运行[=26= 视图时解释的].您实际上可以在定义了列的元数据中看到。

做你想做的唯一方法是 recompile/alter 新列的视图。

这在documentation中有解释:

The view definition is “frozen” at creation time and is not affected by subsequent changes to the definitions of the underlying tables. For example, if a view is defined as SELECT * on a table, new columns added to the table later do not become part of the view, and columns dropped from the table will result in an error when selecting from the view.

您可以拥有一个 text/sql 文件,其中包含所有视图的定义,并且 运行 每次更新表格时都包含该文件。因此,您不需要更新每个视图。

类似的东西:

DROP VIEW IF EXISTS menu_view;
CREATE VIEW menu_view AS
    SELECT * FROM main.menu;

DROP VIEW IF EXISTS table2_view;
CREATE VIEW table2_view AS
    SELECT * FROM main.table2;