视图不可插入,如果它在 FROM 子句中包含子查询

View is not insertable, if it contains sub query in FROM clause

我有一个 mysql view,它在 FROM 子句中有子查询。这个观点是updatable。我尝试更新单个 table 并且效果很好。但我无法插入 table。它说:

Error Code: 1471. The target table action_view of the INSERT is not insertable-into

mysq 视图:

    CREATE OR REPLACE
VIEW `action_view` AS
    SELECT 
        `ca`.`id` AS `id`,
        `cah`.`title` AS `title`,
        `ca`.`idCareActionHead` AS `idCareActionHead`,
        `ca`.`idPeople` AS `idPeople`,
        `ca`.`assignedTo` AS `assignedTo`,
        `ca`.`dueDate` AS `dueDate`,
        `note`.idCareAction AS `idCareAction`
    FROM
       `care_action` `ca`
        JOIN `care_action_head` `cah`
        JOIN `people` `p`
        JOIN (SELECT 
            `cn`.`idCareAction` AS `idCareAction`
        FROM `care_note` `cn`) `note`

    WHERE
        `ca`.`idCareActionHead` = `cah`.`id`
            AND (`ca`.`idPeople` = `p`.`id`)
            AND (`note`.`idCareAction` = `ca`.`id`)

更新查询效果很好:

update action_view set idCareActionHead = 1 where action_view.id =25;

插入出现上述错误的查询:

insert into action_view (idCareActionHead, idPeople) values (12, 4);

我参考了最新的 mysql 文档

https://dev.mysql.com/doc/refman/5.7/en/view-updatability.html1 讨论 SELECT 语句中的子查询,但没有说明 FROM 子句中的子查询。

我的问题是,是否可以在 mysql 的 FROM 子句中插入具有子查询的视图,或者我在这里做错了什么?

首先,我完全不明白为什么要在 from 子句中使用子查询。子查询中没有过滤、分组和格式化数据,您只是 select 来自 table 的单个字段。您可以直接加入 care_note table。

不过,更重要的是MySQL应用了一个非常明智的restriction on inserts into views:

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:

...

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

...

note 子查询的此限制失败,导致您收到错误消息。

更新

反映下面 OP 的评论,即子查询确实包含分组依据和聚合函数 - 上面引用的相同 MySQL 文档也说:

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

• Aggregate functions (SUM(), MIN(), MAX(), COUNT(), and so forth)

• ...

• GROUP BY

...

这意味着子查询肯定是不可更新的。这也意味着视图不能被插入table,但它的其他部分仍然可以更新。