1

I have the following data:

table1:

id  common_criteria        member_id
1       some                 1000
2       some1                 500
3       some                  100
4       some                  200
3       some1                2000

table2

id member_id

The id columns are AUTOINCREMENT PRIMARY KEY on both tables

I need to insert into table2 three new rows (in this case) where common_criteria from table1 = 'some'

Expected result for table2:

id    member_id
1       1000
2       100
3       200

I have tried:

INSERT into table2 (`member_id`) 
VALUES (
 SELECT `member_id` FROM table1 WHERE common_criteria = 'some'
)

But I get a syntax error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT member_id FROM table1 WHERE common_criteria = 'some')' at line 1

2 Answers 2

1

You shouldn't need the VALUES part when you want to get the results from a SELECT. Instead you can simplify it to this:

INSERT into table2 (`member_id`) 
   SELECT `member_id`
   FROM table1 
   WHERE common_criteria = 'some'

and it will insert all the rows returned by the SELECT.


Additional note (since people often ask this): If you had a scenario where some of the values are static every time, then you can do that too quite easily:

INSERT into table2 (`member_id`, `some_other_field`) 
   SELECT `member_id`, 'Static Text' 
   FROM table1 
   WHERE common_criteria = 'some'

In this case "Static Text" will be inserted every time into every row, no matter how many rows are returned (and inserted) as a result of the SELECT.

Sign up to request clarification or add additional context in comments.

Comments

1

You can just do it like this:

INSERT INTO table2 (`member_id`) 
SELECT `member_id` FROM table1 WHERE common_criteria = 'some' 

1 Comment

Thank's ... You have upvote but I will accept ADyson answer because him have first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.