我有一个 mysql View 在 中有子查询发件人 条款。此 View 是可更新的。我尝试更新单个表,效果很好。但我无法插入该表。它说 :
Error Code: 1471. The target table action_view of the INSERT is not insertable-into
mysq View :
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.html 1其中讨论了
SELECT
中的子查询声明,但没有说明 FROM
中关于子查询的任何内容条款。我的问题是,是否可以插入具有子查询的 View
FROM
mysql 中的子句还是我在这里做错了什么?
最佳答案
首先,我不明白你为什么在 from
中使用子查询条款。子查询中没有对数据进行过滤、分组、格式化,您只需从表中选择一个字段。您只需加入 care_note
直接表。
然而,更重要的是 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
,此限制失败子查询,导致您收到错误消息。更新
反射(reflect)下面 OP 的评论,即子查询确实包含 group by 和聚合函数 - 上面引用的相同 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
...
这意味着子查询绝对不可更新。这也意味着 View 不能插入,但它的其他部分仍然可以更新。
关于mysql - View 不可插入,如果它在 FROM 子句中包含子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49029139/