Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this possible with sql?

Tags:

sql

mysql

insert

Is it possible to do something like this:

INSERT INTO table(col1, col2) VALUES(something_from_another_table, value);

With something_from_another_table being a SQL command? Like, is there something I can do that's equivelant to:

INSERT INTO table(col1, col2) VALUES((SELECT value FROM table2 WHERE id = 3), value);
like image 881
Andrew Avatar asked Apr 14 '10 14:04

Andrew


3 Answers

Yes

INSERT INTO table(col1, col2) 
SELECT value1, 'value2' FROM table2 WHERE id = 3

Where value1 is the value from the 'other table' and value2 is a constant that you've included in that select statement.

like image 171
LesterDove Avatar answered Oct 21 '22 20:10

LesterDove


Try this:

INSERT INTO table(col1, col2) 
SELECT table2.value1, value2 FROM table2 WHERE table2.id = 3;
like image 42
Jeffrey L Whitledge Avatar answered Oct 21 '22 19:10

Jeffrey L Whitledge


http://dev.mysql.com/doc/refman/5.1/en/insert-select.html

take a look especially in the examples.

I would recommend reading full syntax of SELECT, UPDATE, DELETE and INSERT SQL commands to begin with. Then expand to subqueries and DDL.

Go slowly and work out examples.

like image 40
Unreason Avatar answered Oct 21 '22 19:10

Unreason