简体   繁体   中英

sync records of two tables in the same database in MYSQL

I have two tables with some same fields like:

Table A: fname, lname, address, age, email, mobile, website, blog Table B: fname, lname, address, age, email

Both these tables are used by different modules on my website. I want to sync the first five fields of both tables in such a way that whenever a new row is added or an existing row is modified in Table A, the Table B is updated automatically and vice versa.

For Example.

  1. A user created a new record in Table A. Now the Table B should also be updated with this new information. and vice versa if a user creates a new record in Table B, the Table A should also be updated with this new information.

  2. A user modified a record in Table A. Now the Table B should also be updated with this modified information. and vice versa if a user modifies a new record in Table B, the Table A should also be updated with this modified information.

How can I achieve this. I thought of using triggers but would it not create an inifinite loop resulting is server error!

Is any field among those 5 guaranteed to be unique? You could add a conditional to the trigger to check to see if that field exists before inserting the record in the table.

You might want to rethink the design also. Storing duplicate records in 2 places seems a little scaring. You're going to have to have triggers for updates, inserts, and deletes.

If u just need to update one table in case the other table gets updated, Instead of creating a table (as a part of some other table), create a View which is also like a table but virtual (not real).
but since u've asked for both sides update.

What I believe is that you should go back little back of this problem....and tell us why u need to update both the tables according to the other table,,,
Because you are just keeping duplicate data at two places that is of no need.

So, try to think whether it can be done without creating two tables, or something like create one table and one view for partial columns requirement.

It is not an answer to your problem, but I am trying to solve your problem in an optimized way which is good for everyone's health.... Hope you understood what i tried to tell. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM