我有一张叫的桌子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”列需要一些逻辑,因此您必须自己解决这个问题。实现此目的的一种方法是在插入内容中使用select:
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'));
请注意,正如上面的示例数据所示,这将创建一个零索引列。
还有其他方法可以执行此操作(存储过程或触发器),但这是一种快速的,数据库提供者不可知的方法,可以实现您正在寻找的内容(我认为)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句