Jump to content

Recommended Posts

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) ) 

Link to comment
https://forums.phpfreaks.com/topic/243542-query-to-insert-or-update/
Share on other sites

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....

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.