如何在MySQL数据库中实现这种自动增量

时间:2018-08-30 02:20:13

标签: javascript mysql database jdbc indexing

我有一张名为animal的桌子。

此表中有四列

  1. 动物
  2. AnimalIndex
  3. 品种
  4. BreedIndex

所有这四列应为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")

我的索引将自动增加。我该如何实现?

2 个答案:

答案 0 :(得分:2)

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

动物:

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

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

还有其他方法可以执行此操作(存储过程或触发器),但这是一种快速且与数据库提供商无关的方法,可以实现您正在寻找的内容(我认为)。

答案 1 :(得分:2)

请注意,@ rmlan解释的解决方案非常有用,简单并且与数据库无关。但是,它可能无法在企业级应用程序中很好地工作,特别是在插入率很高的情况下。

在这种情况下,并行线程可能会产生相同的id。

对于这些情况,我建议使用触发器。