【问题标题】:Insert multi information for smae id为同一个ID插入多个信息
【发布时间】:2021-10-13 21:38:17
【问题描述】:

如何在 MYSQL 中插入一个 id 多输入,如下所示:当我激活自动增量时,无需重复“车辆代码”

谢谢 问候

【问题讨论】:

    标签: python mysql entity-relationship


    【解决方案1】:

    您有两个entities车辆轮胎。它们之间是多对多的关系

    所以你需要三个表。

    vehicle:
    
    vehicle_id(PK)   vehicle_no  vehicle_code
    1                AST-001     V-01
    2                BTU-001     Q-99
    
    tyre:
    
    tyre_id(PK)  size   pattern (size and pattern are part of a UNIQUE key)
    1            AB     BB
    2            AC     CC
    3            AD     XX
    4            AE     YY
    5            AF     ZZ
    6            AG     AA
    7            PA     R1
    
    vehicle_tyre:  (to handle the many-to-many relationship)
    
    vehicle_id  tyre_id  tyre_no   (all columns are part of a composite primary key)
    1           1         1
    1           2         2
    1           3         3
    1           4         4
    1           5         5
    1           6         6
    2           1         7    (this vehicle has four tyres, all the same)
    2           2         7
    2           3         7
    2           4         7
    

    当您的应用需要插入新类型的轮胎时,您可以执行此操作。 IGNORE 与 (size, pattern) 上的 UNIQUE 索引一起防止插入重复轮胎而无需大量额外工作。

    INSERT IGNORE INTO tyre (size, pattern) VALUES (?, ?);  #[size, pattern]
    

    当您有新的车辆要插入时,您可以这样做。您运行以下三个 SQL 语句,并为车辆上的每个轮胎重复最后一个。

    INSERT INTO vehicle (vehicle_no, vehicle_code) VALUES (?,?);  #[no, code]
    SET @vehicle_id := LAST_INSERT_ID();
    INSERT INTO vehicle_tyre (vehicle_id, tyre_id, tyre_no)
                 SELECT       @vehicle_id, tyre_id, ?
                   FROM tyre
                  WHERE size = ? AND pattern = ?;   #[tyre_no, size, pattern]
    

    LAST_INSERT_ID() 是在vehicle_tyre 表中正确获取vehicle_id 的技巧。请注意:使用 python 执行 INSERT 后,您可以使用 cursor.lastrowidconnection.insert_id() 获取 LAST_INSERT_ID() 值。 See this.

    【讨论】:

    • 感谢您的帮助!我会尝试并反馈!
    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2014-09-04
    • 2012-07-10
    • 2014-08-06
    • 2018-10-08
    • 2018-09-08
    • 1970-01-01
    相关资源
    最近更新 更多