anser316 Posted March 30, 2008 Share Posted March 30, 2008 Hi, I have a problem with inserting data into my 'total_stock' table. I want to calculate 'total_stock' by adding all 'stock'. I have been trying to insert data in 'stocks' table, within inserting data in 'total_stock' as i cant add into stock table first as i need the foreign which i havent created. create table total_stock( t_id smallint(2) unsigned not null, total_stock float not null, constraint total_pk primary key (t_id)); create table stocks s_id smallint(2) unsigned not null, stock int not null, t_id smallint(2) unsigned not null, constraint stocks_pk primary key (s_id) constraint stocks_tid_fk foreign key (t_id) REFERENCES total_stock(t_id)); Quote Link to comment https://forums.phpfreaks.com/topic/98617-problem-with-inserting-data-in-tables/ Share on other sites More sharing options...
mwasif Posted March 30, 2008 Share Posted March 30, 2008 What you have tried so far? Quote Link to comment https://forums.phpfreaks.com/topic/98617-problem-with-inserting-data-in-tables/#findComment-504727 Share on other sites More sharing options...
anser316 Posted March 30, 2008 Author Share Posted March 30, 2008 insert into table_stock (t_id) values (1); insert into stocks (s_id,stock,t_id) values (1,10,1); insert into stocks (s_id,stock,t_id) values (2,20,1); UPDATE table_stock SET total_stock=SUM(stock) WHERE t_id=1 I dont know how to sum the stock and store it properly Quote Link to comment https://forums.phpfreaks.com/topic/98617-problem-with-inserting-data-in-tables/#findComment-504829 Share on other sites More sharing options...
mwasif Posted March 30, 2008 Share Posted March 30, 2008 You need to use subquery to SUM. UPDATE total_stock SET total_stock = (SELECT SUM(stock) FROM stocks WHERE stocks.t_id = total_stock.t_id) WHERE t_id=1 Quote Link to comment https://forums.phpfreaks.com/topic/98617-problem-with-inserting-data-in-tables/#findComment-504857 Share on other sites More sharing options...
cooldude832 Posted March 30, 2008 Share Posted March 30, 2008 why do u need to get a SUM if you can always retrieve it on demand??? Quote Link to comment https://forums.phpfreaks.com/topic/98617-problem-with-inserting-data-in-tables/#findComment-504899 Share on other sites More sharing options...
mwasif Posted March 30, 2008 Share Posted March 30, 2008 why do u need to get a SUM if you can always retrieve it on demand??? This approach is very usefull when you have million of rows and you need to fetch that data frequently. Quote Link to comment https://forums.phpfreaks.com/topic/98617-problem-with-inserting-data-in-tables/#findComment-504906 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.