Select/generate counter value in ordered by select in MySQL

lainatnavi :

I am aware that there's no sequence generator in MySQL. Even though I am wondering if there is a way to achieve this:
I have the following select where I need to generate a field with a counter

mysql> select name, age, hobby, ' ' counter from t order by name;
+------------+------+--------------+---------+
| name       | age  | hobby        | counter |
+------------+------+--------------+---------+
| Mark       |   21 | Soccer       |         |
| Mark       |   21 | Football     |         |
| pizzipizzi |    7 | cronchcronch |         |
| Steve      |   23 | Basketball   |         |
| Steve      |   23 | Coding       |         |
| Steve      |   23 | Soccer       |         |
+------------+------+--------------+---------+
5 rows in set (0.01 sec)

Desired result set (the counter resets to 0 for each new name):

+------------+------+--------------+---------+
| name       | age  | hobby        | counter |
+------------+------+--------------+---------+
| Mark       |   21 | Soccer       |    0    |
| Mark       |   21 | Football     |    1    |
| pizzipizzi |    7 | cronchcronch |    0    |
| Steve      |   23 | Basketball   |    0    |
| Steve      |   23 | Coding       |    1    |
| Steve      |   23 | Soccer       |    2    |
+------------+------+--------------+---------+

Any help would be much appreciated.

Strawberry :

Consider the following:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,name VARCHAR(20) NOT NULL
,age INT NOT NULL
,hobby VARCHAR(20) NOT NULL
);

INSERT INTO my_table (name,age,hobby) VALUES
('Mark',21,'Soccer'),
('Mark',21,'Football'),
('pizzipizzi',7,'cronchcronch'),
('Steve',23,'Basketball'),
('Steve',23,'Coding'),
('Steve',23,'Soccer');

SELECT x.*
     , COUNT(y.id)-1 counter 
  FROM my_table x 
  JOIN my_table y 
    ON y.name = x.name 
   AND y.age = x.age 
   AND y.id <= x.id 
 GROUP  
    BY x.id;
+----+------------+-----+--------------+---------+
| id | name       | age | hobby        | counter |
+----+------------+-----+--------------+---------+
|  1 | Mark       |  21 | Soccer       |       0 |
|  2 | Mark       |  21 | Football     |       1 |
|  3 | pizzipizzi |   7 | cronchcronch |       0 |
|  4 | Steve      |  23 | Basketball   |       0 |
|  5 | Steve      |  23 | Coding       |       1 |
|  6 | Steve      |  23 | Soccer       |       2 |
+----+------------+-----+--------------+---------+

Note that in MySQL 8.0+ you have more options

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=13815&siteId=1