自动根据表中的另一列在Mysql 5.7中增加一列

时间:2018-04-19 08:33:10

标签: mysql database auto-increment mysql-5.7

我有一张这样的表

+------------------+------------------+------+-----+-------------------+-----------------------------+
| Field            | Type             | Null | Key | Default           | Extra                       |
+------------------+------------------+------+-----+-------------------+-----------------------------+
| id               | int(10) unsigned | NO   | PRI | NULL              | auto_increment              |
| user_id          | int(10) unsigned | NO   |     | NULL              |                             |
| arena_ids        | json             | NO   |     | NULL              |                             |
| organization_id  | int(10) unsigned | NO   | MUL | NULL              |                             |
| type             | tinyint(4)       | NO   |     | NULL              |                             |
| registration_fee | double           | YES  |     | NULL              |                             |
| tax_group_id     | int(10) unsigned | YES  | MUL | NULL              |                             |
| from_date        | date             | YES  |     | NULL              |                             |
| to_date          | date             | YES  |     | NULL              |                             |
| status           | varchar(10)      | YES  |     | NULL              |                             |
| comments         | varchar(100)     | YES  |     | NULL              |                             |
| created_at       | datetime         | NO   |     | CURRENT_TIMESTAMP |                             |
| updated_at       | datetime         | YES  |     | NULL              | on update CURRENT_TIMESTAMP |
| deleted_at       | datetime         | YES  |     | NULL              |                             |
+------------------+------------------+------+-----+-------------------+-----------------------------+

现在,在此表中,我需要再添加一列serial number 而且serial numberauto_increment,但在我的情况下,我需要增加serial_number,直到organization_id更改,如果organization_id更改,那么 serial_number从1开始。

`serial_number`   `organization_id`
     1                   1
     2                   1
     1                   2
     3                   1
     2                   2 

当我阅读文档时,我发现了一些像这样的例子,但我在这里我必须更新而不是创建

CREATE TABLE animals (
    grp ENUM('fish','mammal','bird') NOT NULL,
    id MEDIUMINT NOT NULL AUTO_INCREMENT,
    name CHAR(30) NOT NULL,
    PRIMARY KEY (grp,id)
) 

+--------+----+---------+
| grp    | id | name    |
+--------+----+---------+
| fish   |  1 | lax     |
| mammal |  1 | dog     |
| mammal |  2 | cat     |
| mammal |  3 | whale   |
| bird   |  1 | penguin |
| bird   |  2 | ostrich |
+--------+----+---------+

如何在更新查询中实现此功能。

0 个答案:

没有答案