S
S
Svyatoslav Nemato2017-07-24 09:52:29
MySQL
Svyatoslav Nemato, 2017-07-24 09:52:29

How to auto-number fields in MySql?

Fields id(int) | user_id(int)
How to make the id field numbered in order, depending on the user_id
Example

id | user_id
_____________
1 | 1
2 | 1
3 | 1
1 | 2
2 | 2
4 | 1
3 | 2
1 | 3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Holub, 2017-07-24
@denman1985

In the manual:
https://dev.mysql.com/doc/refman/5.7/en/example-au...
There is an example similar to yours:

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)
) ENGINE=MyISAM;

INSERT INTO animals (grp,name) VALUES
    ('mammal','dog'),('mammal','cat'),
    ('bird','penguin'),('fish','lax'),('mammal','whale'),
    ('bird','ostrich');

SELECT * FROM animals ORDER BY grp,id;

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

The main idea is to create a composite Primary Key and Auto_Increment.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question