MySQL Insert into multiple tables? (Database normalization?)

前端 未结 8 2260
庸人自扰
庸人自扰 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:36

    have a look at mysql_insert_id()

    here the documentation: http://in.php.net/manual/en/function.mysql-insert-id.php

    0 讨论(0)
  • 2020-11-22 02:37

    fairly simple if you use stored procedures:

    call insert_user_and_profile('f00','http://www.f00.com');
    

    full script:

    drop table if exists users;
    create table users
    (
    user_id int unsigned not null auto_increment primary key,
    username varchar(32) unique not null
    )
    engine=innodb;
    
    drop table if exists user_profile;
    create table user_profile
    (
    profile_id int unsigned not null auto_increment primary key,
    user_id int unsigned not null,
    homepage varchar(255) not null,
    key (user_id)
    )
    engine=innodb;
    
    drop procedure if exists insert_user_and_profile;
    
    delimiter #
    
    create procedure insert_user_and_profile
    (
    in p_username varchar(32),
    in p_homepage varchar(255)
    )
    begin
    declare v_user_id int unsigned default 0;
    
    insert into users (username) values (p_username);
    set v_user_id = last_insert_id(); -- save the newly created user_id
    
    insert into user_profile (user_id, homepage) values (v_user_id, p_homepage);
    
    end#
    
    delimiter ;
    
    call insert_user_and_profile('f00','http://www.f00.com');
    
    select * from users;
    select * from user_profile;
    
    0 讨论(0)
提交回复
热议问题