简体   繁体   中英

Mysql auto-incremtent for sub/group entries

I have parent and child entries in my database like:

| ID   | Team   |
| 100  | Team_1 |
| 200  | Team_2 |
| 300  | Team_3 |

And players like

| ID | Team_ID   | Player   |
| 1  | 100       | Player_1 |
| 2  | 300       | Player_2 |

Now i need a column with auto-incremtent based for every Team. It should start new count every time a new team will be added.

A fontend table should like:

  • Team players:
  • 100_1 = ...
  • 100_2 = ...
  • 200_1 = ...
  • 200_2 = ...
  • 200_3 = ...
  • 300_1 = ...
  • ...

How to do this in mysql / php?

Thanks.

If you just want to display the data at the front end it can be achieved as below using MySQL query:

SET @prev_value = NULL;
SET @rank_count = 1;
SELECT id, Team_ID, 
CONCAT(Team_ID, "_", CASE
    WHEN @prev_value = Team_ID THEN @rank_count := @rank_count + 1
    WHEN @prev_value := Team_ID THEN @rank_count := 1
END) as Team_players
FROM player
ORDER BY Team_ID

SQL Demo: http://sqlfiddle.com/#!9/5df40d/12

You need to alter your table,add the needed column then create a trigger on this table after "insert" to fill it with your goal string teamId_playerId. Good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM