MySQL Insert into multiple tables? (Database normalization?)

前端 未结 8 2261
庸人自扰
庸人自扰 2020-11-22 01:56

I tried searching a way to insert information in multiple tables in the same query, but found out it\'s impossible? So I want to insert it by simpl

8条回答
  •  醉话见心
    2020-11-22 02:18

    What would happen, if you want to create many such records ones (to register 10 users, not just one)? I find the following solution (just 5 queryes):

    Step I: Create temporary table to store new data.

    CREATE TEMPORARY TABLE tmp (id bigint(20) NOT NULL, ...)...;
    

    Next, fill this table with values.

    INSERT INTO tmp (username, password, bio, homepage) VALUES $ALL_VAL
    

    Here, instead of $ALL_VAL you place list of values: ('test1','test1','bio1','home1'),...,('testn','testn','bion','homen')

    Step II: Send data to 'user' table.

    INSERT IGNORE INTO users (username, password)
    SELECT username, password FROM tmp;
    

    Here, "IGNORE" can be used, if you allow some users already to be inside. Optionaly you can use UPDATE similar to step III, before this step, to find whom users are already inside (and mark them in tmp table). Here we suppouse, that username is declared as PRIMARY in users table.

    Step III: Apply update to read all users id from users to tmp table. THIS IS ESSENTIAL STEP.

    UPDATE tmp JOIN users ON tmp.username=users.username SET tmp.id=users.id
    

    Step IV: Create another table, useing read id for users

    INSERT INTO profiles (userid, bio, homepage) 
    SELECT id, bio, homepage FROM tmp
    

提交回复
热议问题