Network_ninja Posted August 2, 2011 Share Posted August 2, 2011 Is it possible to do a single query that update or insert a record? For example I have to tables... table1 table2 tranid code description tranid code description 1 001 zero zero one 1 001 one zero zero 2 002 zero zero two 2 002 two zero zero 3 003 zero zero three 3 003 three zero zero 4 004 zero zero four 5 005 zero zero five my question is i have to update the record in table2. If the code in table1 already exist in table2 update the description. If the code in table1 does not exist in table2 insert the record. so after the query table2 will look sumting lyk dis: table2 tranid code description 1 001 zero zero one 2 002 zero zero two 3 003 zero zero three 4 004 zero zero four 5 005 zero zero five This is my current code that is not working: SELECT * FROM `table1` if((SELECT COUNT(tranid) FROM table2 WHERE table2.code=table.code) == 0,(INSERT INTO table2 VALUES('',table1.code,table2.code) ),(UPDATE table2 SET table2.description=table.1description WHERE table2.code=table1.code) ) Quote Link to comment https://forums.phpfreaks.com/topic/243542-query-to-insert-or-update/ Share on other sites More sharing options...
Pikachu2000 Posted August 2, 2011 Share Posted August 2, 2011 Look at INSERT . . . ON DUPLICATE KEY UPDATE syntax. Quote Link to comment https://forums.phpfreaks.com/topic/243542-query-to-insert-or-update/#findComment-1250528 Share on other sites More sharing options...
Network_ninja Posted August 2, 2011 Author Share Posted August 2, 2011 This is my new code. But still not working well. INSERT INTO table2 (code,description) SELECT code,description FROM table1 ON DUPLICATE KEY UPDATE description=(SELECT description FROM table1) by the way I am using the field code to check if it exist in the other table... not the tranid which is my primary and is auto-increment field.. tnx.... Quote Link to comment https://forums.phpfreaks.com/topic/243542-query-to-insert-or-update/#findComment-1250544 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.