Mysql
 sql >> Database >  >> RDS >> Mysql

È possibile inserire dati in una vista MySQL?

Se stai utilizzando inner join e la tua vista contiene tutte le colonne nelle tabelle di base, la tua vista potrebbe essere aggiornabile. Tuttavia, per una vista aggiornabile con più tabelle, INSERT può funzionare se si inserisce in una singola tabella. Puoi dividere la tua operazione di inserimento in più INSERT dichiarazioni.

Potresti voler controllare il seguente articolo per ulteriori informazioni sull'argomento:

Considera il seguente esempio:

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);

Ora creiamo una vista:

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)

Il seguente INSERT fallisce:

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 

Ma possiamo dividerlo in due operazioni:

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)

Risultato:

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)