Vaak wil je rijen van de ene tabel naar de andere verplaatsen. MySQL doet dat netjes met INSERT INTO ... SELECT: gegevens worden uit een brontabel gekopieerd naar een doeltabel, terwijl bestaande rijen in de doeltabel onaangeroerd blijven.
Syntax
Alle kolommen insertten:
INSERT INTO table2 SELECT * FROM table1;
Bepaalde kolommen insertten:
INSERT INTO table2 column1, column2.. SELECT column1, column2, .. FROM table1;
Voorbeelden
We gebruiken twee voorbeeldtabellen, Users en Customers
Users +------+--------------+-------------+ | id | user_name | location | +------+--------------+-------------+ | 1 | Jim | London | | 4 | Rocky | US | | 7 | Dan | Italy | | 3 | Bill | France | +------+--------------+-------------+
Customers +-------+------------------+--------+------------+ | id | customer_name | age | location | +-------+------------------+--------+------------+ | 11 | John | 23 | US | | 14 | Roger | 36 | London | | 17 | Will | 29 | Spain | | 13 | Bob | 34 | Japan | +-------+------------------+--------+------------+
Enkele kolommen insertten:
mysql> INSERT INTO users (user_name, location) SELECT customer_name, location FROM customers; +------+--------------+-------------+ | id | user_name | location | +------+--------------+-------------+ | 1 | Jim | London | | 4 | Rocky | US | | 7 | Dan | Italy | | 3 | Bill | France | | 11 | John | US | | 14 | Roger | London | | 17 | Will | Spain | | 13 | Bob | Japan | +-------+-------------+-------------+
Dezelfde bewerking, maar beperkt tot klanten uit de 'US':
INSERT INTO users (user_name, location) SELECT customer_name, location FROM customers WHERE location='US';
De kolommen die je selecteert moeten qua aantal en datatype overeenkomen met de kolommen in de INSERT. Bestaande rijen blijven staan; er worden alleen nieuwe aan toegevoegd.