Larcy
Larcy

Reputation: 299

How to use insert query where one of the value is a result of a subquery

I have two table such as table1 and table2. Below shows the following sample fields:

table1 : id, amount
table2 : id, total_amount

I want to insert a value to my table2 using an insert query. But the problem is I want one of the values of my insert query to be the result of a subquery inside an insert statement. For example:

INSERT INTO table2(id, total_amount) VALUES(111, (SELECT SUM(amount) from table1 WHERE id=1));

I knew that the above query is wrong. How can I do the query that can be able to insert to table2 where one of the value to be inserted to table2 is the resulting query from my table1 as shown above?

Can anyone help me with this? Thanks

Upvotes: 1

Views: 51

Answers (3)

Vamshi .goli
Vamshi .goli

Reputation: 520

try with this

 $sql=mysql_fetch_assoc(mysql_query("SELECT SUM(amount) as tot from table1 WHERE id=1")
 INSERT INTO table2(id, total_amount) VALUES(111,$sql['tot']);

Upvotes: 0

SMA
SMA

Reputation: 37023

Try something like:

 INSERT INTO table2(SELECT 111, SUM(amount) 
                    FROM table1 WHERE id=1);

Upvotes: 0

juergen d
juergen d

Reputation: 204756

INSERT INTO table2(id, total_amount) 
SELECT 111, SUM(amount) from table1 WHERE id=1

Upvotes: 2

Related Questions