Split table into two tables with foreign keys

佐手、 提交于 2019-12-02 02:59:10

You could do this with a TRIGGER.

Here's some pseudo-code to illustrate this technique:

DELIMITER $$

DROP TRIGGER IF EXISTS tr_b_ins_comments $$

CREATE TRIGGER tr_b_ins_comments BEFORE INSERT ON comments FOR EACH ROW BEGIN
  DECLARE v_uid INT DEFAULT NULL;

  /* BEGIN pseudo-code */
  IF (new.uid IS NULL)
  THEN
    -- check for existing user with matching name and email address
    select user_id
    into v_uid
    from your_user_table
    where name = new.name 
    and email = new.email;

    -- if no match, create a new user and get the id
    IF (v_uid IS NULL)
    THEN
      -- insert a new user into the user table
      insert into your_user_table ...

      -- get the new user's id (assuming it's auto-increment)
      set v_uid := LAST_INSERT_ID();
    END IF;

    -- set the uid column
    SET new.uid = v_uid;
  END IF;

  /* END pseudo-code */
END $$

DELIMITER ;
berkes

I searched further and found that, apparently, it is not possible to update/insert more then one table in a single query in MySQL.

The solution would, therefore have to be scripted/programmed outside of SQL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!