ds355020 2019-01-07 04:48
浏览 43
已采纳

同步MySQL数据库中不同表的两行

I have a table named clients, in that table there's two columns of importance; id and client. I have a secondary table in the same database named calendar. I really want the two columns of id and client in the calendar table to sync with the ones in client table.

Right now I am using this PHP to execute this in MySQL:

INSERT IGNORE INTO calendar (id, client) SELECT id, client FROM clients;

Is there a better way of accomplish this task? Maybe a built in function in MySQL that I have overlooked or something like that?

  • 写回答

1条回答 默认 最新

  • dongliaoqiang8524 2019-01-07 04:57
    关注

    Use Triggers : The MySQL trigger is a database object that is associated with a table. It will be activated when a defined action is executed for the table.

    The trigger can be executed when you run one of the following MySQL statements on the table: INSERT, UPDATE and DELETE and it can be invoked before or after the event.

    You can make trigger when you insert or update a row in main table and make the changes in another table

    Example:

    DELIMITER $$
    
    CREATE TRIGGER my_sync_trigger 
    AFTER INSERT ON `clients` for each row
    begin
    INSERT INTO calender (id,client)
    Values (new.id, new.client);
    END$$
    
    DELIMITER ;
    

    "new" stands for the new value inserted into clients table. The same value will be inserted into id and client column in calender.

    Note: single quotes are removed from table name because quotes effectively make it a string literal instead of a proper identifier. DELIMITER command will change the ending of each statement from ";" to "$$" so that MySQL is not confused with ";" inside and outside the trigger

    Make similar triggers for update and delete also

    Simple guide for examples and syntax: http://www.mysqltutorial.org/create-the-first-trigger-in-mysql.aspx

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错