首页 > 解决方案 > 为 smae id 插入多项信息

问题描述

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

在此处输入图像描述

感谢和问候

标签: pythonmysqlentity-relationship

解决方案


您有两个实体车辆轮胎。他们彼此之间是多对多的关系

所以你需要三个表。

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 与 UNIQUE 索引一起(size, pattern)可防止插入重复轮胎而无需大量额外工作。

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.lastrowid或获取 LAST_INSERT_ID() 值connection.insert_id()看到这个。


推荐阅读