python - 为 smae id 插入多项信息
问题描述
如何在 MYSQL 中插入一个 id 多输入,如下所示:当我激活自动增量时,无需重复“车辆代码”
感谢和问候
解决方案
您有两个实体:车辆和轮胎。他们彼此之间是多对多的关系
所以你需要三个表。
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()
。看到这个。
推荐阅读
- react-native-flatlist - 在本机反应中为分区列表生成数据
- android - 将两个 SQL 列加载到列表视图中但只需要显示第一列 Android
- python - 关于打包第一个PyPi项目的问题
- java - 为多模块 Maven 项目构建多个组件 zip
- r - 从 webscraper 更改 R 中的日期但无法转换
- twilio - 小型客户服务团队的 Twilio 呼叫路由/管理
- java - 跨类层次结构重构 try-catch
- javascript - 网站标题 - 为每个字母应用不同的颜色
- netsuite - SuiteScript 2.0 搜索过滤器抛出 UNEXPECTED _ERROR
- swift - CustomCell 标签值更改时如何更新 UITableView?