[按MySQL中的select顺序选择/生成计数器值

问题描述 投票:1回答:1

我知道MySQL中没有序列发生器。即使我想知道是否有一种方法可以实现:我有以下选择,需要在其中生成带有计数器的字段

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)

所需的结果集(每个新名称的计数器都重置为0:]

+------------+------+--------------+---------+
| 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    |
+------------+------+--------------+---------+

任何帮助将不胜感激。

mysql generator counter
1个回答
1
投票

请考虑以下内容:

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 |
+----+------------+-----+--------------+---------+

注意,在MySQL 8.0+中,您有更多选择

© www.soinside.com 2019 - 2024. All rights reserved.