tags:

views:

115

answers:

5

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);
+2  A: 

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.

Unreason
+18  A: 

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.

LesterDove
+5  A: 

Try this:

INSERT INTO table(col1, col2) 
SELECT table2.value1, value2 FROM table2 WHERE table2.id = 3;
Jeffrey L Whitledge
A: 

You definately can. It should work similar as the example below;

INSERT INTO Store_Information (store_name, Sales, Date)
(SELECT store_name, Sales, Date FROM Sales_Information WHERE Year(Date) = 2010)
Rob
A: 

when you specify the keyword "Values" on the insert statement you are trying to insert just a value. the current way to do that is assigning the value of the "something_from_another_table" into a variable and then, make your insert

DECLARE @ANYVALUE AS VARCHAR(40)
SELECT @ANYVALUE = ANYFIELD FROM table2 WHERE id = 3
INSERT INTO table1 (FIELD1, FIELD2) VALUES(@ANYVALUE, VALUE2)

On this way always will insert one record. the other correct way will insert n record as the where statement can filter.

INSERT INTO Store_Information (store_name, Sales, Date)
(SELECT store_name, Sales, Date FROM Sales_Information WHERE Year(Date) = 2010)
a52