Jump to content

Recommended Posts

Hello,

So i have query that takes data from table a and inserts into table b (which is empty) and updates field copied_date in table a.

 

so something like this

 

INSERT INTO `b`(`ba`,`bb`,`bc`) SELECT `aa,`,`ab`,`ac` FROM `a`';

UPDATE `a` SET `Copied_date` = 'NOW()';

 

I want to know how this query actually works and if I can simplify it even more. Does it INSERT INTO first of all the data then goes back and UPDATES? or does it work all in one query kind of way?

 

 

Thanks

Edited by dev-ria
Link to comment
https://forums.phpfreaks.com/topic/270116-insert-and-update-in-same-query/
Share on other sites

The query works by reading the SELECT part first, then using the values returned as a multi-line INSERT statement. The MySQL manual should provide you with more details on this, if you need it. :)

 

As for how to simplify it: About the only thing I can see is to set the copied_date field to a timestamp, which updates on change. Again, the MySQL manual contains information on how to accomplish that. ;)

timestamp wouldn't make any difference, as it changes on update, not select. There is no more simple way to do the above, but a cleaner way would be to use a triger on table b that updates the copy_date of table a after each record is inserted. then you would only need to have the insert statement (but you would need to write the trigger in the database, so it would actualy total more code than you have already).

I think you want to use the 'ON DUPLICATE KEY UPDATE' clause. This is an add-on to the INSERT command which will update rows with matching primary keys, and insert when there is no match. (You will probably get a better response in the MYSQL thread.)

thanks guys for the info! how can i use ON DUPLICATE KEY UPDATE? what does it do exactly? because the table (table b ) am inserting into does not have any data so therefore would not have any duplicates. I looked at mysql dev but dont really understand what it's doing exactly.

Edited by dev-ria

ON DUPLICATE KEY solves the question you seem to be asking in the thread TITLE, but has nothing to do with the thread's actual CONTENTS.

 

A trigger is the proper solution to this.

Edited by ManiacDan
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.