tags:

views:

853

answers:

6

So say I want to...

insert into tableA, 2 variables from tableB, but only rows that are in tableB that have 1 of the variables equal to a certain thing...

hmm let's see if I can be more specific...

i want to create a new row in tableA with the userid and courseid from tableB for every row of tableB that has a courseid of 11

please advise

+16  A: 
INSERT
INTO    tableA (col1, col2)
SELECT  userid, courseid
FROM    tableB
WHERE   courseid = 11
Quassnoi
or select the appropriate fields instead of *
GoodEnough
+4  A: 

Well not knowing what columns you have in tableA, I'd say:

insert into tableA
select 
    userid,
    courseid 
from tableB where 
courseid=11
Ian Devlin
Oops, forgot to format it, thanks Russ.
Ian Devlin
I guess @Quassnoi hit submit a few seconds earlier... so many votes, given that your answers are identical. Unfair, but that's life, hey! ;-)
Cerebrus
I upvoted this answer too :)
Quassnoi
Hehe no worries, it doesn't bother me! Thanks to you both.
Ian Devlin
A: 
INSERT INTO TableA (userid, courseid)

SELECT userid, courseid FROM TableB
WHERE courseid = 11

That should do it for you.

Gregory A Beamer
A: 

You didn't mention which database you're using.

MS Access, for me, has proven to be very buggy when trying to do something like this.

42
A: 

You may use SELECT INTO if you are creating a new table using existing data:

SELECT <columns here> INTO tableA FROM tableB WHERE <restrictions here>

If you want to insert existing data into an existing table, you must use:

INSERT INTO tableA (<destination columns>) SELECT <source columns> FROM tableB WHERE <restrictions here>

As described in other answers

vezult
You cannot select into an existing table
HLGEM
I stand corrected. Thanks.
vezult
A: 

insert into tableA(column1,column2,column3) select column1,column2,column3 from table B

You are right with the general notation, though there was a specific set of columns asked in the question. You will find, over time, that if you do not add significant new information with an answer, you will gain little or no reputation by answering older questions which already have a good answer.
Jonathan Leffler