向视图插入数据mysql,是否可以将数据插入MySQL视图?

I made a MySQL view with 4 tables. Is it possible to insert data into the view and have MySQL automatically pass the data into the right table?

解决方案

If you are using inner joins, and your view contains all the columns in the base tables, then your view might be updatable. However, for a multiple-table updatable view, INSERT can work if it inserts into a single table. You could split your insert operation into multiple INSERT statements.

You may want to check out the following article for more information on the topic:

Consider the following example:

CREATE TABLE table_a (id int, value int);

CREATE TABLE table_b (id int, ta_id int, value int);

INSERT INTO table_a VALUES (1, 10);

INSERT INTO table_a VALUES (2, 20);

INSERT INTO table_a VALUES (3, 30);

INSERT INTO table_b VALUES (1, 1, 100);

INSERT INTO table_b VALUES (2, 1, 200);

INSERT INTO table_b VALUES (3, 2, 300);

INSERT INTO table_b VALUES (4, 2, 400);

Now let's create a view:

CREATE VIEW v AS

SELECT a.id a_id, b.id b_id, b.ta_id, a.value v1, b.value v2

FROM table_a a

INNER JOIN table_b b ON (b.ta_id = a.id);

SELECT * FROM v;

+------+------+-------+------+------+

| a_id | b_id | ta_id | v1 | v2 |

+------+------+-------+------+------+

| 1 | 1 | 1 | 10 | 100 |

| 1 | 2 | 1 | 10 | 200 |

| 2 | 3 | 2 | 20 | 300 |

| 2 | 4 | 2 | 20 | 400 |

+------+------+-------+------+------+

4 rows in set (0.00 sec)

The following INSERT fails:

INSERT INTO v (a_id, b_id, ta_id, v1, v2) VALUES (3, 5, 3, 30, 500);

-- ERROR 1393 (HY000): Can not modify more than one base table through a join view

But we can split it into two operations:

INSERT INTO v (a_id, v1) VALUES (3, 30);

-- Query OK, 1 row affected (0.00 sec)

INSERT INTO v (b_id, ta_id, v2) VALUES (5, 3, 500);

-- Query OK, 1 row affected (0.00 sec)

Result:

SELECT * FROM v;

+------+------+-------+------+------+

| a_id | b_id | ta_id | v1 | v2 |

+------+------+-------+------+------+

| 1 | 1 | 1 | 10 | 100 |

| 1 | 2 | 1 | 10 | 200 |

| 2 | 3 | 2 | 20 | 300 |

| 2 | 4 | 2 | 20 | 400 |

| 3 | 5 | 3 | 30 | 500 |

+------+------+-------+------+------+

6 rows in set (0.00 sec)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值