javascript - 如何在 MySQL 数据库中实现这种自动增量
问题描述
我有一张桌子叫animal
.
在这个表中有四列
- 动物
- 动物指数
- 品种
- 品种指数
所有这四个列都应该是primary key
我希望它们在逻辑上自动递增,这意味着得到这样的东西。
| Animal| AI | Breed | BI |
----------------------------
| dog | 1 | Akita | 1 |
| cat | 2 | Persan | 1 |
| dog | 1 | Barbet | 2 |
| dog | 1 | Boxer | 3 |
| eagle | 3 | Bald | 1 |
所以如果我输入一个类型的查询
INSERT INTO animal (Animal, Breed) VALUES("dog", "Akita")
我的索引会自动增加。我怎样才能做到这一点?
解决方案
我会考虑使用不同的数据模型。也许更关系友好:
动物:
| id | name |
--------------
| 1 | dog |
| 2 | cat |
| 3 | eagle |
品种:
| id | name | breed_idx | animal_id |
---------------------------------------|
| 1 | Akita | 0 | 1 |
| 2 | Persan | 0 | 2 |
| 3 | Barbet | 1 | 1 |
| 4 | Boxer | 2 | 1 |
| 5 | Bald | 1 | 3 |
Mysql 可以轻松地处理 id 列的自动递增,但由于“breed_idx”列需要一些逻辑,因此您必须自己处理。您可以完成它的一种方法是在插入中使用选择:
insert into breed (name, breed_idx, animal_id) values('Shar pei', (select count(*) from breed where animal_id = (select id from animal where name = 'dog')), (select id from animal where name = 'dog'));
请注意,这将创建一个零索引列,如我上面的示例数据所示。
还有其他方法可以做到这一点(存储过程或触发器),但这是一种快速且与数据库提供者无关的方法来实现(我认为)您正在寻找的东西。
推荐阅读
- javascript - 当 React 中的代码更改其值时,如何在输入上触发 onChange 事件?
- python - 如何在tendermint旁边运行烧瓶作为守护进程
- javascript - ChartJS 条形图
- python - 将来自 flaskSQLAlchemy 的对象数据填充到 wtfforms 字段中
- angular - 使用 ng2-dragula 复制
- powershell - 在 powershell 脚本中隐藏我的 Octopus API 密钥
- windows - 无法连接 Pentaho 数据集成和 SVN
- bokeh - Bokeh RuntimeError: 模型必须只属于一个文档,Selection(id='1057', ...) 已经在一个文档中
- php - 计算每个值在列中出现的次数
- python - 如何在 Python 中找到满足条件(最大和最小阈值)的所有可能组合?