首页 > 解决方案 > 如何在 MySQL 数据库中实现这种自动增量

问题描述

我有一张桌子叫animal.

在这个表中有四列

  1. 动物
  2. 动物指数
  3. 品种
  4. 品种指数

所有这四个列都应该是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")

我的索引会自动增加。我怎样才能做到这一点?

标签: javascriptmysqldatabasejdbcindexing

解决方案


我会考虑使用不同的数据模型。也许更关系友好:

动物:

| 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'));

请注意,这将创建一个零索引列,如我上面的示例数据所示。

还有其他方法可以做到这一点(存储过程或触发器),但这是一种快速且与数据库提供者无关的方法来实现(我认为)您正在寻找的东西。


推荐阅读