Reputation: 299
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
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
Reputation: 37023
Try something like:
INSERT INTO table2(SELECT 111, SUM(amount)
FROM table1 WHERE id=1);
Upvotes: 0
Reputation: 204756
INSERT INTO table2(id, total_amount)
SELECT 111, SUM(amount) from table1 WHERE id=1
Upvotes: 2