Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select from one table and insert into another

Tags:

sql

mysql

I've got two tables.

Table_A (nid, vid, type, title, uid)

Table_B (id, questiontext)

I need to insert records from Table_B into Table_A. I tried this:

INSERT INTO Table_A (nid, vid, type, title, uid) VALUES ('', '', multichoice', (SELECT questiontext from Table_B), '1') 

but it's throwing an error.

What should be the correct statement?

UPD: I should add that nid is autoincrement and the value of vid should be same as nid.

like image 669
nrk Avatar asked Mar 04 '10 07:03

nrk


People also ask

How do I pull data from one table to another table?

The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.

Can we use insert and select together?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.

How do you insert the result of a query into a table?

To create an Insert Results queryFrom the Query Designer menu, point to Change Type, and then click Insert Results. In the Choose Target Table for Insert Results Dialog Box, select the table to copy rows to (the destination table).


Video Answer


2 Answers

Have you tried

INSERT INTO Table_A (nid, vid, type, title, uid)  SELECT  '',          '',          'multichoice',          questiontext ,         '1' from    Table_B 

Have a look at INSERT ... SELECT Syntax

like image 57
Adriaan Stander Avatar answered Sep 29 '22 17:09

Adriaan Stander


You should use the following SQL query:

INSERT INTO Target(A, B, C)   SELECT A, B, C     FROM Source 
like image 40
Matthias Meid Avatar answered Sep 29 '22 18:09

Matthias Meid