MySQL - How to insert into table that has many-to-many relationship

前端 未结 1 914
走了就别回头了
走了就别回头了 2021-01-30 01:53

I have a table of persons. Each person has a property and many persons may have a certain property. So this is a many-to-many relationship. This is the schema:

C         


        
1条回答
  •  醉梦人生
    2021-01-30 02:34

    Here is what i ended up doing. I hope it helps someone.

    INSERT INTO persons (firstname,lastname) VALUES ('John','Doe');
    SET @person_id = LAST_INSERT_ID();
    
    INSERT IGNORE INTO properties (property) VALUES ('property_A');
    SET @property_id = LAST_INSERT_ID();
    INSERT INTO has_property (person_id,property_id) VALUES(@person_id, @property_id);
    
    INSERT IGNORE INTO properties (property) VALUES ('property_B');
    SET @property_id = LAST_INSERT_ID();
    INSERT INTO has_property (person_id,property_id) VALUES(@person_id, @property_id);
    
    INSERT IGNORE INTO properties (property) VALUES ('property_C');
    SET @property_id = LAST_INSERT_ID();
    INSERT INTO has_property (person_id,property_id) VALUES(@person_id, @property_id);
    

    0 讨论(0)
提交回复
热议问题